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

后端 未结 7 1045
感动是毒
感动是毒 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:09

    Agree with above, SharpZipLib , for creating .zip files in .NET, it seems a very popular option.

    As for 'send'ing, if you mean via SMTP/Email, you will need to use the System.Net.Mail name space. The System.Net.Mail.Attachment Class documentation has an example of how to send a file via email

    Scratch the above, by the time I posted this I see you meant return via HTTP Response.

    0 讨论(0)
  • 2020-12-05 12:10

    DotNetZip creates the stream without saving any resources on the server, so you don't have to remember to erase anything. As I said before, its fast and intuitive coding, with an efficient implementation.

    Moshe

    0 讨论(0)
  • 2020-12-05 12:13

    I would second the vote for SharpZipLib to create the Zip file. Then you'll want to append a response header to the output to force the download dialog.

    http://aspalliance.com/259

    should give you a good starting point to achieve that. You basically need to add a response header, set the content type and write the file to the output stream:

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

    That last line could be changed to a Response.Write(filecontents) if you don't want to save to a temp file.

    0 讨论(0)
  • 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<String>
            zip.AddFiles(filesToInclude, "files")            
            zip.Save(Response.OutputStream)
        End Using
        Response.Close
    
    0 讨论(0)
  • 2020-12-05 12:16

    I modified some codes as below, i use System.IO.Compression

     public static void Zip(HttpResponse Response, HttpServerUtility Server, string[] pathes)
        {
            Response.Clear();
            Response.BufferOutput = false;         
    
            string archiveName = String.Format("archive-{0}.zip",
                                              DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
            Response.ContentType = "application/zip";
            Response.AddHeader("content-disposition", "filename=" + archiveName);
    
            var path = Server.MapPath(@"../TempFile/TempFile" + DateTime.Now.Ticks);
            if (!Directory.Exists(Server.MapPath(@"../TempFile")))
                Directory.CreateDirectory(Server.MapPath(@"../TempFile"));
    
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            var pathzipfile = Server.MapPath(@"../TempFile/zip_" + DateTime.Now.Ticks + ".zip");
            for (int i = 0; i < pathes.Length; i++)
            {
                string dst = Path.Combine(path, Path.GetFileName(pathes[i]));
                File.Copy(pathes[i], dst);
            }
            if (File.Exists(pathzipfile))
                File.Delete(pathzipfile);
            ZipFile.CreateFromDirectory(path, pathzipfile);
            {
                byte[] bytes = File.ReadAllBytes(pathzipfile);
                Response.OutputStream.Write(bytes, 0, bytes.Length);
            }
            Response.Close();
            File.Delete(pathzipfile);
            Directory.Delete(path, true);
        }  
    

    this code gets some list containing list of files copy them in temp folder , create temp zip file then read all bytes of that file and send bytes in response stream, finaly delete temp file and folder

    0 讨论(0)
  • 2020-12-05 12:27

    I'm sure others will recommend SharpZipLib

    How do you intend to "send" it. .NET has built in Libraries for email via SMTP

    EDIT

    In that case you'll want to capture the output stream from SharpZipLib and write it directly to the Response. Just make sure you have the correct Mimetype set in the Response Headers (application/zip) and make sure you don't Response.Write anything else to the user.

    0 讨论(0)
提交回复
热议问题