Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

download multiple files as zip in .net

Tags:

c#

.net

download

I have a program which needs to download multiple files at once. I can download a single file by using this single file download, but it doesn't work for multiple.

How can one download multiple files at once in such as as zip file?

like image 768
deepu Avatar asked Oct 21 '10 05:10

deepu


1 Answers

You need to pack files and write a result to a response. You can use SharpZipLib compression library.

Code example:

Response.AddHeader("Content-Disposition", "attachment; filename=" + compressedFileName + ".zip");
Response.ContentType = "application/zip";

using (var zipStream = new ZipOutputStream(Response.OutputStream))
{
    foreach (string filePath in filePaths)
    {
        byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);

        var fileEntry = new ZipEntry(Path.GetFileName(filePath))
        {
            Size = fileBytes.Length
        };

        zipStream.PutNextEntry(fileEntry);
        zipStream.Write(fileBytes, 0, fileBytes.Length);
    }

    zipStream.Flush();
    zipStream.Close();
}
like image 156
bniwredyc Avatar answered Sep 25 '22 11:09

bniwredyc