打印本文 打印本文  关闭窗口 关闭窗口  
实时zip压缩下载整个目录
作者:不详  文章来源:不详  点击数  更新时间:2003/10/21 20:27:14  文章录入:ahui  责任编辑:ahui

要下载整个目录,一般方法是一个个文家下载或ftp工具
现在用SharpZipLib就能实现实时zip压缩下载整个目录

SharpZipLib提供了多种压缩算法的支持,纯csharp代码,参见
http://www.icsharpcode.net/OpenSource/SharpZipLib/default.asp

原理是通过递归方法将每个文件压缩到ZipOutputStream,然后下载

代码和范例如下:

<%@ Import namespace="ICSharpCode.SharpZipLib.Zip" %>
<%@ Import Namespace="System.IO" %>
<script language="c#" runat="server">
 ZipOutputStream zos=null;
 String strBaseDir="";
 void dlZipDir(string strPath,string strFileName){
  MemoryStream ms =null;
  Response.ContentType = "application/octet-stream";
  strFileName=HttpUtility.UrlEncode(strFileName).Replace('+',' ');
  Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName+".zip");
  ms = new MemoryStream();
  zos = new ZipOutputStream(ms);
  strBaseDir=strPath+"\\";
  addZipEntry(strBaseDir);
  zos.Finish();
  zos.Close();
  Response.Clear();
  Response.BinaryWrite(ms.ToArray());
  Response.End();
 }
 
 void addZipEntry(string PathStr){
  DirectoryInfo di= new DirectoryInfo(PathStr);
  foreach(DirectoryInfo item in di.GetDirectories()){
   addZipEntry(item.FullName);
  }
  foreach(FileInfo item in di.GetFiles()){
   FileStream fs = File.OpenRead(item.FullName);
   byte[] buffer = new byte[fs.Length];
   fs.Read(buffer, 0, buffer.Length);
   string strEntryName=item.FullName.Replace(strBaseDir,"");
   ZipEntry entry = new ZipEntry(strEntryName);
   zos.PutNextEntry(entry);
   zos.Write(buffer, 0, buffer.Length);
   fs.Close();
  }
 }
 void Page_Load(){
  dlZipDir(Server.MapPath("."),"test");
 }
</script>

打印本文 打印本文  关闭窗口 关闭窗口