20 09 46 18
支付宝
微信
扫描二维码打赏
更多详情(暂无)

C#将文件压缩成一个文件流,供前端下载

  直接上代码供大家参考。。。

  前端页面就是一个下载的Button。。  

<body>
    <form id="form1" runat="server">
    <div>
    <asp:button ID="btn_down" runat="server" text="下载" onclick="btn_down_Click" />
    </div>
    </form>
</body>

  后台代码:

复制代码
  protected void btn_down_Click(object sender, EventArgs e)
        {
            var name = Server.MapPath("huage");
            //if (!Directory.Exists(name))
            //    throw new FileNotFoundException("")
            var zipName = "test";
            DownZip(name, zipName,9);             
        }
        private void DownZip(string dirname, string zipfile, int level = 6, string password = "")
        {
            MemoryStream ms = new MemoryStream();//支持存储区为内存的流
            ZipOutputStream zos = new ZipOutputStream(ms);
            if (password != "")
                zos.Password = password;

            zos.SetLevel(level);
            AddZipEntry(dirname, zos, dirname);          
            zos.Finish();
            zos.Close();          
            Response.Clear();
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlDecode(zipfile,System.Text.Encoding.UTF8) + ".zip");
            Response.BinaryWrite(ms.ToArray());
            ms.Close();
            Response.Flush();
            Response.End();
        }
        private void AddZipEntry(string strPath, ZipOutputStream zos, string baseDirName)
        {
            DirectoryInfo dir = new DirectoryInfo(strPath);
            foreach (FileSystemInfo item in dir.GetFileSystemInfos())
            {
                if ((item.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    AddZipEntry(item.FullName, zos, baseDirName);
                }
                else
                {
                    FileInfo f_item = (FileInfo)item;
                    using (FileStream fs = f_item.OpenRead())
                    {
                        byte[] buffer = new byte[(int)fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        ZipEntry entry = new ZipEntry(f_item.FullName.Replace(baseDirName, ""));
                        zos.PutNextEntry(entry);
                        zos.Write(buffer, 0, buffer.Length);
                    }
                }
            }
        }
复制代码

压缩的代码的没看懂的话,可以参考我的文章:

C#使用ICSharpCode.SharpZipLib.dll进行文件的压缩与解压

posted @   华临天下  阅读(1475)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示