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进行文件的压缩与解压
本文只是记录学习心得,如果有误请提示博主加以修正。。。
谢谢您那么帅气,还能看完小主的文言文!