【问题标题】:How to use ZipPackage to create a zip如何使用 ZipPackage 创建一个 zip
【发布时间】:2013-09-19 13:06:29
【问题描述】:

我在 MSDN 上看到过关于 ZipPackage class 的文档。

那里的例子不是很有用,谁能提供这个类的例子?

【问题讨论】:

    标签: c# zip


    【解决方案1】:

    这里是一个例子,请注意:
    - ZipPackage 似乎不压缩
    - 生成的 zip 包含不需要的文件“[Content_Types].xml”
    - System.IO.Compression 因为 .Net 4.5 似乎是一个不错的选择

    您必须在 Visual Studio 中添加对“WindowsBase”的引用(不带“System.IO”之类的前缀)

    using System;
    using System.Linq;
    using System.Text;
    using System.IO.Packaging;
    using System.IO;
    
    namespace TestZip
    {
     public static class  Program
     {
      public static void Main(string[] args)
      {
       byte[] data = Encoding.UTF8.GetBytes(String.Join("\n", new string[1000].Select(s => "Something to zip.").ToArray()));
       byte[] zippedBytes;
       using(MemoryStream zipStream = new MemoryStream())
       {
        using (Package package = Package.Open(zipStream, FileMode.Create))
        {
         PackagePart document = package.CreatePart(new Uri("/test.txt", UriKind.Relative), "");
         using (MemoryStream dataStream = new MemoryStream(data))
         {
          document.GetStream().WriteAll(dataStream);
         }     
        }    
        zippedBytes = zipStream.ToArray();
       }
       File.WriteAllBytes("test.zip", zippedBytes);
      }
    
      private static void WriteAll(this Stream target, Stream source)
      {
       const int bufSize = 0x1000;
       byte[] buf = new byte[bufSize];
       int bytesRead = 0;
       while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
        target.Write(buf, 0, bytesRead);
      }
     }
    }
    

    【讨论】:

      【解决方案2】:

      看看这个代码项目 -

      C# Use Zip Archives without External Libraries

      【讨论】:

        猜你喜欢
        • 2010-09-22
        • 1970-01-01
        • 2013-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-16
        • 1970-01-01
        相关资源
        最近更新 更多