2010-10-21 49 views

回答

22

您需要打包文件並將結果寫入響應。 您可以使用SharpZipLib壓縮庫。

代碼示例:

Response.AddHeader("Content-Disposition", "attachment; filename=" + compressedFileName + ".zip"); 
Response.ContentType = "application/zip"; 

using (var zipStream = new ZipOutputStream(Response.OutputStream)) 
{ 
    foreach (string filePath in filePaths) 
    { 
     byte[] fileBytes = System.IO.File.ReadAllBytes(filePath); 

     var fileEntry = new ZipEntry(Path.GetFileName(filePath)) 
     { 
      Size = fileBytes.Length 
     }; 

     zipStream.PutNextEntry(fileEntry); 
     zipStream.Write(fileBytes, 0, fileBytes.Length); 
    } 

    zipStream.Flush(); 
    zipStream.Close(); 
} 
+0

這太棒了......值得讚賞。你知道是否有任何實時的方法來知道壓縮的大小?我希望能夠告訴我的用戶如果壓縮,他們將下載的內容的大小。 – pearcewg 2011-10-06 22:46:00

+1

@pearcewg,我認爲在這種情況下解決方案取決於您的要求。如果你知道什麼是檔案內容,你可以在頁面生成之前壓縮文件,並顯示檔案的大小。如果檔案內容可能有所不同,那麼這是一項非常重要的任務。我的想法是:1.將關於壓縮文件大小的信息放入數據庫中2.根據壓縮的統計數據顯示壓縮文件的近似大小。 – bniwredyc 2011-10-07 06:01:12

+0

工作就像一個魅力。謝謝 – 2013-11-18 06:03:26

1
+0

是否有可能創建rar格式,,, – deepu 2010-10-21 05:47:35

+0

@deepu你可能不得不使用rar.exe創建一個rar文件。 – Fedearne 2010-10-21 05:56:58

+0

此主題有關於RAR的一些信息:http://stackoverflow.com/questions/1025863/read-content-of-rar-files-using-c。 – 2010-10-21 05:59:18

0

3個庫,我知道的是SharpZipLib(多功能格式),DotNetZip(一切ZIP)和ZipStorer(小型和緊湊型)。沒有鏈接,但他們都在codeplex上,並通過谷歌搜索。許可證和確切功能各不相同。

快樂編碼。

3

這是如何做到這一點的DotNetZip方式:DI擔保DotNetZip因爲我已經用它,它是迄今爲止C#最簡單的壓縮庫我遇到:)

檢查http://dotnetzip.codeplex.com/

http://dotnetzip.codeplex.com/wikipage?title=CS-Examples&referringTitle=Examples

在ASP.NET中創建可下載的zip。本示例在ASP.NET回發方法中動態創建zip文件,然後通過Response.OutputStream將該zip文件下載到請求的瀏覽器。沒有在磁盤上創建zip存檔。

public void btnGo_Click (Object sender, EventArgs e) 
{ 
    Response.Clear(); 
    Response.BufferOutput= false; // for large files 
    String ReadmeText= "This is a zip file dynamically generated at " + System.DateTime.Now.ToString("G"); 
    string filename = System.IO.Path.GetFileName(ListOfFiles.SelectedItem.Text) + ".zip"; 
    Response.ContentType = "application/zip"; 
    Response.AddHeader("content-disposition", "filename=" + filename); 

    using (ZipFile zip = new ZipFile()) 
    { 
    zip.AddFile(ListOfFiles.SelectedItem.Text, "files"); 
    zip.AddEntry("Readme.txt", "", ReadmeText); 
    zip.Save(Response.OutputStream); 
    } 
    Response.Close(); 
} 
+0

你好..感謝這個漂亮的回覆..但我想知道,我是否可以在添加到zip之前更改文件的名稱(在zip.AddFile命令之前)。我正在討論將要添加到ZIP中的文件,而不是zip文件的文件名。 – 2013-09-26 11:42:19

相關問題