如何使用ZipPackage创建一个压缩包

4

我看过有关ZipPackage 类的MSDN文档。

那里的示例不是很有用,有人能提供一个关于这个类的示例吗?

2个回答

5
这里有一个例子,请注意: - 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);
  }
 }
}

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接