c# 使用ICSharpCode.SharpZipLib.dll实现文件压缩并返回

一、Nuget中下载ICSharpCode.SharpZipLib.dll

二、压缩帮助类实现

/// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="files"></param>
        public static Stream Compress(Dictionary<string, string> files)
        {
            var returnSm = new MemoryStream();
            var zipStream = new MemoryStream();
            using (ZipOutputStream stream = new ZipOutputStream(zipStream))
            {
                foreach (var item in files)
                {
                    string fileName = item.Key;
                    string filePath = item.Value;
                    if (!FileHelper.IsExistFile(filePath)) continue;
                    using (FileStream fs = File.OpenRead(filePath))
                    {
                        byte[] buffer = new byte[4 * 1024];
                        ZipEntry entry = new ZipEntry(fileName);
                        entry.DateTime = DateTime.Now;
                        stream.PutNextEntry(entry);
                        int sourceBytes;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            stream.Write(buffer, 0, sourceBytes);
                        } while (sourceBytes > 0);
                    }
                    stream.Flush();
                }
                stream.Finish();
                zipStream.Seek(0, SeekOrigin.Begin);
                zipStream.CopyTo(returnSm);
            }
            returnSm.Seek(0, SeekOrigin.Begin);
            return returnSm;
        }

三、通过流返回浏览器

                var stream = ZipHelper.Compress(files);
                return File(stream, "application/octet-stream", string.Format("{0}_{1}{2}", "压缩文件", DateTime.Now.ToString("yyyyMMddHHmmss"), ".zip"));
原文地址:https://www.cnblogs.com/tck-blogs/p/10820202.html