简体   繁体   中英

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

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 anything.

Sorry for the confusion. I'm going to generating the zip on the fly for the web user, and sending it to them in the HTTP response. Not in an email.

Mark

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.

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

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.

One concern is the size of the file that you will be streaming to the client. If you use SharpZipLib to build the ZIP in-memory, you don't have any temp files to cleanup, but you'll soon run into memory issues if the files are large and a number of concurrent users are downloading files. (We experienced this pretty frequently when ZIP sizes got to the 200 MB+ range.) I worked around this by the temp file to disk, streaming it to the user, and deleting it when then request completed.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM