ASP.NET 文件打包下载

本文介绍了一种在ASP.NET中实现文件打包并提供下载的方法。通过使用ZipClass压缩类库,将多个文件复制到临时目录并进行压缩,然后提供给用户下载。在下载完成后,会清理临时文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 ASP.NET 文件打包下载

用到ZipClass 文件压缩类 参考 http://blog.youkuaiyun.com/t_t_x_s/article/details/24017713

 

     protected void Button1_Click(object sender, EventArgs e)
        {
           //下载文件
            string path = Server.MapPath("xlt/");
            string copyPath = Server.MapPath("Zip/xlt/");
            FileInfo fi = new FileInfo(path + "ajaxMethod使用方法.txt");
            int i=1;
            while (Directory.Exists(copyPath))
            {
                copyPath = Server.MapPath("Zip/xlt" + i + "/");
                i++;
            }
            Directory.CreateDirectory(copyPath);
            if (fi.Exists) {
                fi.CopyTo(copyPath+fi.Name);
            }
            fi = new FileInfo(path + "恶趣味.xlsx");
            if (fi.Exists)
            {
                fi.CopyTo(copyPath + fi.Name);
            }
            fi = new FileInfo(path + "清恶趣味.xls");
            if (fi.Exists)
            {
                fi.CopyTo(copyPath + fi.Name);
            }
            ZipClass zc = new ZipClass();
            zc.ZipFileMain(copyPath,Server.MapPath("Zip/xlt.zip"),"");
           
         //   DirectoryInfo zipPath = new DirectoryInfo(copyPath);
         //   zipPath.Delete(); //删除文件夹

            //删除文件夹
            DeleteFolder(copyPath);

            Response.Clear();    //解决txt中出现乱码
            Response.ContentType = "application/x-zip-compressed";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode("xlt.zip"));//解决文件名中文乱码
            string filename = Server.MapPath("Zip/xlt.zip");
            Response.TransmitFile(filename);
            Response.End();       //解决txt中出现乱码

            fi = new FileInfo(Server.MapPath("Zip/xlt.zip"));
            fi.Delete(); //删除压缩包

        }


        //删除文件夹
        private void DeleteFolder(string folder){
            if (Directory.Exists(folder))
            {
              
                foreach (string filepath in Directory.GetFileSystemEntries(folder))
                {
                    //循环删除文件
                    if (File.Exists(filepath))
                    {
                        File.Delete(filepath);
                    }
                    //递归删除子文件夹
                    else {
                        DeleteFolder(filepath);
                    }
                }
                Directory.Delete(folder); //删除空文件夹
            }
            else {
                throw new Exception("文件夹 " + folder + "不存在!");
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值