C# 对多个文件进行zip压缩

时间:2022-04-02 01:45:46

本文使用的ICSharpCode.SharpZipLib.dll类库来实现文件压缩,你可以通过Nuget来安装此类库,或者到搜索引擎去搜索一下遍地都是。类库下载下来之后,添加到项目引用就可以了。下面这个函数可以实现压缩多个文件,希望对你有用:

/// <summary>
/// 将多个流进行zip压缩,返回压缩后的流
/// </summary>
/// <param name="streams">key:文件名;value:文件名对应的要压缩的流</param>
/// <returns>压缩后的流</returns>
static Stream PackageManyZip(Dictionary<string, Stream> streams)
{
  byte[] buffer = new byte[6500];
  MemoryStream returnStream = new MemoryStream();
  var zipMs = new MemoryStream();
  using (ZipOutputStream zipStream = new ZipOutputStream(zipMs))
  {
    zipStream.SetLevel(9);
    foreach (var kv in streams)
    {
      string fileName = kv.Key;
      using (var streamInput = kv.Value)
      {
        zipStream.PutNextEntry(new ZipEntry(fileName));
        while (true)
        {
          var readCount = streamInput.Read(buffer, 0, buffer.Length);
          if (readCount > 0)
          {
            zipStream.Write(buffer, 0, readCount);
          }
          else
          {
            break;
          }
        }
        zipStream.Flush();
      }
    }
    zipStream.Finish();
    zipMs.Position = 0;
    zipMs.CopyTo(returnStream, 5600);
  }
  returnStream.Position = 0;
  return returnStream;
}