zoukankan      html  css  js  c++  java
  • 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"));
  • 相关阅读:
    第四周作业
    RHEL6+GFS2+MYSQL高可用
    第三周作业
    第二周作业
    centos7 安装redis 开机启动
    无线网卡连接网络后共享给本地有线网卡使用(Win10)
    第一周作业
    2019.8.13加入博客园
    智力题
    Python入门基础学习(模块,包)
  • 原文地址:https://www.cnblogs.com/tck-blogs/p/10820202.html
Copyright © 2011-2022 走看看