如何在C#ASP.NET中为用户生成和发送.zip文件?

MSt*_*odd 12 c# asp.net zip file

我需要构建并向用户发送zip.

我已经看过做一个或另一个的例子,但不是两个,如果有任何"最佳实践"或任何事情,我很好奇.

对困惑感到抱歉.我将为Web用户动态生成zip,并在HTTP响应中将其发送给他们.不在电子邮件中.

标记

Ada*_*ope 20

我会选择SharpZipLib来创建Zip文件.然后,您需要在输出中附加响应标头以强制下载对话框.

http://aspalliance.com/259

应该为你提供一个很好的起点.您基本上需要添加响应头,设置内容类型并将文件写入输出流:

Response.AppendHeader( "content-disposition", "attachment; filename=" + name );
Response.ContentType = "application/zip";
Response.WriteFile(pathToFile);
Run Code Online (Sandbox Code Playgroud)

如果您不想保存到临时文件,则最后一行可以更改为Response.Write(filecontents).


Che*_*eso 10

DotNetZip使您可以轻松地执行此操作,而无需写入服务器上的磁盘文件.您可以直接将zip存档写入Response流,这将导致下载对话框在浏览器上弹出.

DotNetZip的示例ASP.NET代码

更多示例DotNetZip的ASP.NET代码

剪断:

    Response.Clear();
    Response.BufferOutput = false; // false = stream immediately
    System.Web.HttpContext c= System.Web.HttpContext.Current;
    String ReadmeText= String.Format("README.TXT\n\nHello!\n\n" + 
                                     "This is text for a readme.");
    string archiveName= String.Format("archive-{0}.zip", 
                                      DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")); 
    Response.ContentType = "application/zip";
    Response.AddHeader("content-disposition", "filename=" + archiveName);

    using (ZipFile zip = new ZipFile())
    {
        zip.AddFiles(f, "files");            
        zip.AddFileFromString("Readme.txt", "", ReadmeText);
        zip.Save(Response.OutputStream);
    }
    Response.Close();
Run Code Online (Sandbox Code Playgroud)

或者在VB.NET中:

    Response.Clear
    Response.BufferOutput= false
    Dim ReadmeText As String= "README.TXT\n\nHello!\n\n" & _
                              "This is a zip file that was generated in ASP.NET"
    Dim archiveName as String= String.Format("archive-{0}.zip", _
               DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"))
    Response.ContentType = "application/zip"
    Response.AddHeader("content-disposition", "filename=" + archiveName)

    Using zip as new ZipFile()
        zip.AddEntry("Readme.txt", "", ReadmeText, Encoding.Default)
        '' filesToInclude is a string[] or List<String>
        zip.AddFiles(filesToInclude, "files")            
        zip.Save(Response.OutputStream)
    End Using
    Response.Close
Run Code Online (Sandbox Code Playgroud)