我遇到同样的问题,我有一个嵌入式.exe和一个包含大量子文件夹的数据文件夹。为了解决这个问题,我还使用了zip来获取VS中资源的文件夹。但现在我的问题......
如何在运行时打开压缩文件夹?我需要打开,解压缩并保存在临时区域,还是可以以某种方式打开我的内存并从那里使用它们?
.exe是在临时区域创建的,但我希望能够在内存中使用它...
或者我可以直接在资源文件夹中解压缩吗?
非常满满的答案......
答案 0 :(得分:3)
以下是将嵌入式zip文件添加到临时文件夹并解压缩的示例。
private string _tempPath = Environment.GetEnvironmentVariable("TEMP") + @"\";
private string _zipPath = Environment.GetEnvironmentVariable("TEMP") + @"\" + @"MyZip.zip";
/// <summary>
/// Extracts the contents of a zip file to the
/// Temp Folder
/// </summary>
private void ExtractZip()
{
try
{
//write the resource zip file to the temp directory
using (Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("<Namespace>.Resources.<filename>.zip"))
{
using (FileStream bw = new FileStream(_zipPath,FileMode.Create))
{
//read until we reach the end of the file
while (stream.Position < stream.Length)
{
//byte array to hold file bytes
byte[] bits = new byte[stream.Length];
//read in the bytes
stream.Read(bits, 0, (int)stream.Length);
//write out the bytes
bw.Write(bits, 0, (int)stream.Length);
}
}
stream.Close();
}
//extract the contents of the file we created
UnzipFile(_zipPath, _tempPath);
//or
System.IO.Compression.ZipFile.ExtractToDirectory(_zipPath,_tempPath);
}
catch (Exception e)
{
//handle the error
}
}
public void UnzipFile(string zipPath, string folderPath)
{
try
{
if (!File.Exists(zipPath))
{
throw new FileNotFoundException();
}
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
Shell32.Shell objShell = new Shell32.Shell();
Shell32.Folder destinationFolder = objShell.NameSpace(folderPath);
Shell32.Folder sourceFile = objShell.NameSpace(zipPath);
foreach (var file in sourceFile.Items())
{
destinationFolder.CopyHere(file, 4 | 16);
}
}
catch (Exception e)
{
//handle error
}
}