【问题标题】:How to zip and unzip folders and its sub folders in Silverlight?如何在 Silverlight 中压缩和解压缩文件夹及其子文件夹?
【发布时间】:2011-10-28 07:07:28
【问题描述】:

我有一个 Windows Phone 应用程序。我正在使用 SharpZipLib 压缩文件夹及其子文件夹。这只是压缩文件夹,但文件夹内的数据没有被压缩。谁能指导我如何做到这一点?

我的代码:

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);
            }
        }

【问题讨论】:

  • 还有另一个库:dotnetzip.codeplex.com。最终它可以与这个库一起使用吗?
  • SharpZipLib 不可能吗?

标签: zip windows-phone-7.1 windows-phone-7


【解决方案1】:

我想你会发现 this guide 很有帮助。

以上链接的摘录

ZipFile 对象提供了一个名为 AddDirectory() 的方法 接受参数目录名。这种方法的问题是 它不会在指定目录中添加文件,而是 而只是在 zip 文件中创建一个目录。做这个 工作,您需要通过循环获取该目录中的文件 该目录中的所有对象,并一次添加一个。我曾是 能够通过创建一个递归函数来完成此任务 钻取您想要的文件夹的整个目录结构 压缩。下面是函数的sn-p。

我猜你也面临同样的问题,文件夹被添加到 zip 文件中,但内容和子文件夹没有被压缩。

希望这会有所帮助。

【讨论】:

  • @ Abhinav - 感谢您的回复。我会试试这个。
【解决方案2】:

查看over here 以获取有关如何使用 SharpZipLib 压缩包含嵌套文件夹的根文件夹的代码示例。

【讨论】: