简体   繁体   English

如何使用ZipPackage创建一个zip

[英]How to use ZipPackage to create a zip

I've seen the document on MSDN about the ZipPackage class . 我已经在MSDN上看到有关ZipPackage类的文档。

The example there is not very useful, can anyone provide an example about this class? 那里的例子不是很有用,有人可以提供有关此类的例子吗?

Here an example, note that: 这里有一个例子,注意:
- ZipPackage seem to do not compress -ZipPackage似乎不压缩
- The generated zip has an undesired file "[Content_Types].xml" -生成的zip包含不需要的文件“ [Content_Types] .xml”
- System.IO.Compression since .Net 4.5 seems to be a good alternative -自.Net 4.5以来, System.IO.Compression似乎是一个不错的选择

You have, in Visual Studio, to add reference to "WindowsBase" (without prefix like "System.IO.") 您必须在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);
  }
 }
}

take a look at this code project - 看看这个代码项目-

C# Use Zip Archives without External Libraries . C#使用Zip存档而无需外部库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM