Delen via


DotNetZip now can save directly to ASP.NET Response.OutputStream

Did you ever want to zip up a file within an ASP.NET page, and then send it as a download for the requesting browser?  The DotNetZip lib works within ASP.NET, and a recent update, available in the v1.5 preview release, allows you to create a zip file and save it directly to Response.OutputStream, with no intermediate file i/o, no saving the zip file to a directory on the server, no memorystreams or byte arrays to cache the content.

The code looks like this:

 public void btnGo_Click (Object sender, EventArgs e)
{
  Response.Clear();
  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(Response.OutputStream)) {
    // Add to the zip archive, the file selected in the dropdownlist.
    zip.AddFile(ListOfFiles.SelectedItem.Text, "files");
    // Add a boilerplate copyright file into the zip.
    zip.AddFile"\static\Copyright.txt", "");
    // The string ReadmeText becomes the content for an entry in the zip archive, with the filename "Readme.txt".
    zip.AddStringAsFile(ReadmeText, "Readme.txt", "");
    zip.Save();
  }

  Response.End();
}

This example assumes there is a DropDownList named ListOfFiles that contains a list of files. But of course you could get the list of files anywhere. And it goes without saying that you can add more than one file.

Simple, easy.

You need to get the 1.5 release of DotNetZip to use this new feature.

Comments

  • Anonymous
    June 05, 2008
    Amazing tool, just what i was looking for!

  • Anonymous
    October 09, 2008
    Thank you very much. But how to get the length of the zip stream, so I can apply it to .AddHeader("Content-Length")

  • Anonymous
    October 13, 2008
    Typically you don't explicitly set content-length in the application.  ASP.NET buffers the output and automatically appends the correct content length.  

  • Anonymous
    October 29, 2008
    Thanks for the answer. But I tried again, no length content is appended on the download dialog. The code I'm using is just copied from this page. Could you please shed some light on it?

  • Anonymous
    November 04, 2008
    I think you should try the discussion forums on www.codeplex.com/DotNetZip .