2010-10-21 52 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

相关问题