Creating zip file on the fly from a collection of database stored binary files

Sep 27, 2012 at 12:33 PM

Hi there,

Struggling to get my code working for adding a collection of Byte files from the database into a zip file to download on the fly.  Can anyone give me a point in the right direction?  I'm using the latest version.

Here's what I have so far:

string folder = dtFiles[0].UploadGuid;
string zipName = (dtProof[0].Name + "_" + dtProof[0].Postcode).Replace(" ", "") + ".zip";

try
{
    Response.Clear();
    Response.BufferOutput = false;
    Response.ContentType = "application/zip";
    Response.AddHeader("content-disposition", "filename=" + zipName);
    MemoryStream ms = new MemoryStream();
    using (ZipOutputStream zip = new ZipOutputStream(ms))
    {   
        foreach (DataRow row in dtFiles)
        {
            Byte[] fileByte = (Byte[])row["FileBinary"];
            zip.PutNextEntry(row["Filename"].ToString());
            zip.Write(fileByte, 0, fileByte.Length);
        }
        Response.OutputStream.Write(zip);
    }

    Response.Close();
}

The build fails at the Response.OutputStream line, but I'm not sure it's right even up to then. 

Any help appreciated.

Ian

Sep 27, 2012 at 7:56 PM

ZipOutStream is even writing to destination stream while disposing.  So, when it is disposed (after using) instead use the MemoryStream for writing to Response stream.

Another idea is to use ZipFile-object. After adding all files to it, finish with ZipFile.Save(Response.OutputStream).