SharpZipLib压缩打包多个文件

SharpZipLib是C#开源压缩解压缩组件
SharpZipLib可以很容易将多个文件打包成一个zip包
使用版本:0.85.4.369
1.压缩文件:
using (ZipFile zip = ZipFile.Create(@"E:\test.zip")) 

    zip.BeginUpdate(); 
    zip.Add(@"C:\Test\file\file.txt");
    zip.Add(@"C:\Test\image\image.jpg");
    zip.CommitUpdate(); 
}
注意:这样打包后的zip包是按照文件路径打包的,本例的zip包解压后会是:
解压根目录/Image/image.jpg
解压根目录/File/file.txt
2.压缩Stream或者字符串
我们如何添加字符串或者Stream?这个时候改IStaticDataSource接口闪亮登场了:
namespace ICSharpCode.SharpZipLib.Zip
{
    public interface IStaticDataSource
    {
        Stream GetSource();
    }
}
该接口有个返回Stream的GetSource方法,我们可以实现该接口,从而支持字符串文件或者byte[]的打包。
class StreamDataSource : IStaticDataSource
{
   public byte[] Buffer { getprivate set; }
   public StreamDataSource(byte[] buffer)
   {
     Buffer = buffer;
   }
   public Stream GetSource()
   {
    return new MemoryStream(Buffer);
   }
 }
实现了该接口后,那么我们压缩byte[]代码就十分简单了:
 using (ZipFile zip = ZipFile.Create(destinationFile))
  {
     zip.BeginUpdate();
     foreach (var item in imageUnits)
     {
         buffer = null;
         try
         {
             buffer = GetBytesFromUrl(Path.Combine(imageEntity.DownloadUrl, item.ImagePath));
         }
         catch
         {
         }

         if (buffer != null && buffer.Length > 0)
         {
             StreamDataSource dataSource = new StreamDataSource(buffer);
             zip.Add(dataSource, item.ImagePath);
         }
     }
     zip.CommitUpdate();
   }
原文地址:https://www.cnblogs.com/jeriffe/p/2470112.html