Vivek Mishra Vivek Mishra - 4 years ago 98
C# Question

how to download files in zip format which are stored in database in binary format

I have to download multiple files of pdf and doc type together in zip format.
files are stored in binary format and their extensions are saved in database too.
please describe how to download these files in zip format.
i am using ionic zip for this. I tried the following code but it is not working-

protected void ZipDownload()
{
var list = db.Documents.Where(u => u.userId == (int)Session["usrId"]).Select(u => new { u.doc, u.docname, u.doctype });
ZipFile zip = new ZipFile();
foreach (var file in list)
{
zip.AddEntry(file.docname,(byte[])file.doc.ToArray());
}
var zipMs=new MemoryStream();
zip.Save(zipMs);

zipMs.Seek(0, SeekOrigin.Begin);

zipMs.Flush();
}

Answer Source

to download multiple files in zip format use this-

protected void ZipDownload()
    {
        var list = db.Documents.Where(u => u.userId == (int)Session["usrId"]).Select(u => new { u.doc, u.docname, u.doctype });
        ZipFile zip = new ZipFile();
        foreach (var file in list)
        {

            zip.AddEntry(file.docname, (byte[])file.doc.ToArray());
        }
        var zipMs = new MemoryStream();
        zip.Save(zipMs);
        byte[] fileData = zipMs.GetBuffer();
        zipMs.Seek(0, SeekOrigin.Begin);
        zipMs.Flush();
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=docs.zip ");
        Response.ContentType = "application/zip";
        Response.BinaryWrite(fileData);
        Response.End();

    }

this code is perfectly working.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download