ZipHelper

using ICSharpCode.SharpZipLib.Zip;
using System.Collections.Generic;
using System.IO;

namespace WLYD.Utility.File
{
    /// <summary>
    /// 压缩文件
    /// </summary>
    public static class ZipHelper
    {
        public static byte[] ZipExcel(List<OrderExport> list)
        {
            byte[] buffer = null;
            MemoryStream ms = new MemoryStream();
            using (ZipFile file = ZipFile.Create(ms))
            {
                file.BeginUpdate();

                foreach (var o in list)
                {
                    StreamDataSource ss = new StreamDataSource(o.Ms);
                    file.Add(ss, o.Filename);
                }

                file.CommitUpdate();
                buffer = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);   //读取文件内容(1次读ms.Length/1024M)  
                ms.Flush();
                ms.Close();
            }
            return buffer;
        }
        
    }
    public class StreamDataSource : IStaticDataSource
    {
        public byte[] bytes { get; set; }
        public StreamDataSource(MemoryStream ms)
        {
            bytes = ms.GetBuffer();
        }

        public Stream GetSource()
        {
            Stream s = new MemoryStream(bytes);
            return s;
        }
    }
    public class OrderExport
    {
        public string Filename { get; set; }
        public MemoryStream Ms { get; set; }
    }
}

  

原文地址:https://www.cnblogs.com/wangpd/p/6867389.html