利用SharpZipLib實現實時zip壓縮下載整個目錄

要下載整個目錄,一般方法是一個個文家下載或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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章