ZipFile(Response.OutputStream) no longer supported?

Jul 7, 2009 at 5:43 PM

I recently upgraded to version 1.8 from 1.6 and this code no longer works for creating a new zip file into the Output Stream:

ZipFile zip = new ZipFile(Response.OutputStream)

I get the error:

Cannot resolve constructor 'ZipFile(System.IO.Stream)', candidates are:

ZipFile(string) (in class ZipFile)

ZipFile(System.Text.Encoding) (in class ZipFile)

I have also tried the following method, which does not prompt a zip download, but spits out the file as a jumbled character stream into the browser window:

using (ZipFile zip = new ZipFile())

What is the new method for inserting a new zip file directly into the Output Stream?

Jul 7, 2009 at 6:37 PM
Edited Jul 7, 2009 at 7:12 PM

Yep, the constructors that accept a Stream have been removed.

The way to do it is to use the null (Default) constructor, and then ZipFile.Save(Stream).

If you want to save to Response.OutputStream, then you want to Response.Clear() before beginning to write.  Try something like this:

    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);  
    using (ZipFile zip = new ZipFile())
        // filesToInclude is a IEnumerable (String[] or List etc)
        zip.AddFiles(filesToInclude, "files");
    // Response.End();

The reason you want BufferOutput = false is to prompt downloading immediately, even for large zip files. And the reason you should call Response.Clear() is to clear any prior headers that may have been set, indicating, for example, an incorrect content-type or cache header, which could result in a jumbled character stream in the browser window, when what you want is a "Save As" dialog.

I think a best practice, when generating a ZIP From within ASP.NET, is to use an IHttpHandler (.ashx).  That way you can avoid some overhead that would be incurred using an .aspx.

Jul 7, 2009 at 7:04 PM

Thanks, Cheeso! This works great.