如何在Silverlight中压缩和解压缩文件夹及其子文件夹?
问题描述:
我有一个Windows Phone应用程序。我正在使用SharpZipLib压缩文件夹及其子文件夹。这只是压缩文件夹,但文件夹内的数据没有被压缩。任何人都可以指导我如何做到这一点?如何在Silverlight中压缩和解压缩文件夹及其子文件夹?
我的代码:
private void btnZip_Click(object sender, RoutedEventArgs e)
{
using (IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (string filename in appStore.GetFileNames(directoryName + "/" + "*.txt"))
{
GetCompressedByteArray(filename);
}
textBlock2.Text = "Created file has Zipped Successfully";
}
}
public byte[] GetCompressedByteArray(string content)
{
byte[] compressedResult;
using (MemoryStream zippedMemoryStream = new MemoryStream())
{
using (ZipOutputStream zipOutputStream = new ZipOutputStream(zippedMemoryStream))
{
zipOutputStream.SetLevel(9);
byte[] buffer;
using (MemoryStream file = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
buffer = new byte[file.Length];
file.Read(buffer, 0, buffer.Length);
}
ZipEntry entry = new ZipEntry(content);
zipOutputStream.PutNextEntry(entry);
zipOutputStream.Write(buffer, 0, buffer.Length);
zipOutputStream.Finish();
}
compressedResult = zippedMemoryStream.ToArray();
}
WriteToIsolatedStorage(compressedResult);
return compressedResult;
}
public void WriteToIsolatedStorage(byte[] compressedBytes)
{
IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication();
appStore.CreateDirectory(ZipFolder);
using (IsolatedStorageFileStream zipTemplateStream = new IsolatedStorageFileStream(ZipFolder+"/"+directoryName + ".zip", FileMode.OpenOrCreate, appStore))
using (BinaryWriter streamWriter = new BinaryWriter(zipTemplateStream))
{
streamWriter.Write(compressedBytes);
}
}
答
我想你会发现this guide很有帮助。
从上述链接
zip文件对象提供了一个名为AddDirectory(方法) 摘录接受一个参数目录名。这种方法的问题是 ,它不会将文件添加到指定的目录中,但 只是在zip文件内创建一个目录。要使此 正常工作,您需要通过循环访问该目录中的所有对象并逐个添加它们来获取该目录中的文件。我是 能够通过创建一个递归函数来完成这个任务, 通过你想要的文件夹的整个目录结构钻取 zip。以下是该函数的一个片段。
我想你也面临同样的问题,即文件夹被添加到压缩文件,但内容和子文件夹不压缩。
希望这会有所帮助。
+0
@ Abhinav - 感谢您的回复。我会试试这个。 – Shri
还有另一个库:http://dotnetzip.codeplex.com/。最终它与这个图书馆一起工作? –
SharpZipLib无法实现吗? – Shri