How do I generate and send a .zip file to a user in C# ASP.NET?

后端 未结 7 1074
感动是毒
感动是毒 2020-12-05 11:30

I need to construct and send a zip to a user.

I\'ve seen examples doing one or the other, but not both, and am curious if there are any \'best practices\' or anythin

7条回答
  •  庸人自扰
    2020-12-05 12:14

    DotNetZip lets you do this easily, without ever writing to a disk file on the server. You can write a zip archive directly out to the Response stream, which will cause the download dialog to pop on the browser.

    Example ASP.NET code for DotNetZip

    More example ASP.NET code for DotNetZip

    snip:

        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();
    

    or in 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
            zip.AddFiles(filesToInclude, "files")            
            zip.Save(Response.OutputStream)
        End Using
        Response.Close
    

提交回复
热议问题