In this blog have described how to download multiple files within a zip folder in ASP.NET MVC 4. This is also help full in C# and ASP.NET C#.   Steps are given below.

Step 1: For downloading files in compressed folder (Zip Folder), first you download one DDL file “ICSharpCode.SharpZipLib.Zip”, because this DDL is required for downloading files in zip folder. You can download this DDL from below link.

http://www.icsharpcode.net/opensource/sharpziplib/

Step 2: Add reference of downloaded DDL (ICSharpCode.SharpZipLib.Zip) and used two namespaces in your project which given below.

using ICSharpCode.SharpZipLib.Zip;

using System.IO;

Step 3: Now used below line of code within your action or where you want.

using (var zipStream = new ZipOutputStream(Response.OutputStream))
{
// Give the file name of downloaded zip file
  Response.AddHeader("Content-Disposition", "attachment; filename=Description.zip");
// Define content type
  Response.ContentType = "application/zip";
// Get all file path one by one
  foreach (var path in list)
  {
              // Get every file size
                byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath(path.FilePath));
              // Get every file path
                var fileEntry = new ZipEntry(Path.GetFileName(Server.MapPath(path.FilePath)))
                {
                     Size = fileBytes.Length
                };
        zipStream.PutNextEntry(fileEntry);
        zipStream.Write(fileBytes, 0, fileBytes.Length);
    }
 // Clear and closed zipStream object
  zipStream.Flush();
  zipStream.Close();
}

Step 4: If you want to download single file than try below line of code.

// Define content type 
Response.ContentType = "application/pdf";
// set the file name of file
Response.AppendHeader("Content-Disposition", "attachment; filename=Description.pdf");
// get file path from server side
Response.TransmitFile(Server.MapPath("~/content/Description.pdf"));
Response.End();

Note: Trim or remove blank spaces before file upload and download from file name.

  Modified On Sep-18-2014 01:24:08 PM
  1. Thank you for this, I really appreciate this simple and easy usage of SharpZipLib in MVC 4.
    I had to tweak your code a little to use it in ApiControllers but all in all it worked great.
    Also regarding the Step 4, I had to first create a PDF file so I tried this C# Word component, here is how I directly exported PDF files in ASP.NET in the Controller:

    document.Save(this.Response, Server.MapPath("~/Users/Reports.pdf"));

Leave Comment