本文介绍了如何使用ZipPackage创建一个zip的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在MSDN上看到有关的文档ZipPackage类.

I've seen the document on MSDN about the ZipPackage class.

这个例子不是很有用,任何人都可以提供有关此类的例子吗?

The example there is not very useful, can anyone provide an example about this class?

推荐答案

下面是一个示例,请注意:
-ZipPackage似乎不压缩
-生成的zip包含不需要的文件"[Content_Types] .xml"
- System.IO.Compression 因为.Net 4.5似乎是一个很好的选择

Here an example, note that:
- ZipPackage seem to do not compress
- The generated zip has an undesired file "[Content_Types].xml"
- System.IO.Compression since .Net 4.5 seems to be a good alternative

在Visual Studio中,您必须添加对"WindowsBase"的引用(不带前缀,如"System.IO".)

You have, in Visual Studio, to add reference to "WindowsBase" (without prefix like "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);
  }
 }
}

这篇关于如何使用ZipPackage创建一个zip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:54