asp.net 文件打包下载
[本文来自互联网]
使用的是ICSharpCode.SharpZipLib
下载地址http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.IO; using ICSharpCode.SharpZipLib; using ICSharpCode.SharpZipLib.Zip; namespace UploadifyDemo { public partial class DownLoad : System.Web.UI.Page { //文件夹路径物理路径 string ObjDirPath = "E:\\ctt\\other\\test"; string ZipPath = "downLoad"; string ZipName = "\\downlaod" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm") + ".zip"; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //文件打包 fileToZip(); //下载打包文件 Response.Redirect(ZipPath+ZipName); } } /// /// 文件打包 /// protected void fileToZip() { //判断是否存在 if (Directory.Exists(ObjDirPath)) { //zip保存目录 if (!Directory.Exists(Server.MapPath(ZipPath))) Directory.CreateDirectory(Server.MapPath(ZipPath)); //打开文件夹 DirectoryInfo SourceDir = new DirectoryInfo(ObjDirPath); List listFilePath = new List(); // 得到文件夹里面所有文件路径 foreach (FileSystemInfo file in SourceDir.GetFileSystemInfos()) listFilePath.Add(file.FullName); if (listFilePath.Count > 0) { ZipOutputStream u = new ZipOutputStream(File.Create(Server.MapPath(ZipPath) + ZipName)); //新建压缩文件流 “ZipOutputStream” foreach (string s in listFilePath) { this.AddZipEntry(s, u, out u); } u.Finish(); // 结束压缩 u.Close(); //添加下载链接 //HtmlAnchor a = new HtmlAnchor(); //a.HRef ="downLoad"+ZipName; //a.Title = "点击批量下载"; //a.InnerHtml = "批量下载"; //this.divC.Controls.Add(a); } } } /// /// 压缩文件p为客户端传回来的文件列表:文件名+压缩包的名称 /// /// 文件路径名称 public void ZipFile(string filePath) { ZipOutputStream u = new ZipOutputStream(File.Create(Server.MapPath(ZipPath) + ZipName)); //新建压缩文件流 “ZipOutputStream” this.AddZipEntry(filePath, u, out u); //向压缩文件流加入内容 u.Finish(); // 结束压缩 u.Close(); } /// /// 添加压缩项目 /// /// p 为需压缩的文件或文件夹 /// u为现有的源ZipOutputStream /// out j为已添加“ZipEntry”的“ZipOutputStream” public void AddZipEntry(string p, ZipOutputStream u, out ZipOutputStream j) { //if (Directory.Exists(p)) //文件夹的处理 //{ // DirectoryInfo di = new DirectoryInfo(p); // foreach (DirectoryInfo tem in di.GetDirectories()) //获取子目录 // { // ZipEntry z = new ZipEntry(tem.FullName + "\\ "); //末尾“\\”用于文件夹的标记 // u.PutNextEntry(z); //此句不可少,否则空目录不会被添加 // p = Path .GetFileName (tem.FullName); // this.AddZipEntry(p, u, out u); //递归 // } // foreach (FileInfo temp in di.GetFiles()) //获取此目录的文件 // { // p = Path.GetFileName(temp.FullName); // this.AddZipEntry(p, u, out u); //递归 // } //} if (File.Exists(p)) //文件的处理 { u.SetLevel(9); //压缩等级 FileStream f = File.OpenRead(p); byte[] b = new byte[f.Length]; f.Read(b, 0, b.Length); //将文件流加入缓冲字节中 ZipEntry z = new ZipEntry(Path.GetFileName (p)); u.PutNextEntry(z); //为压缩文件流提供一个容器 u.Write(b, 0, b.Length); //写入字节 f.Close(); } j = u; //返回已添加数据的“ZipOutputStream” } } }