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.
Nibaal Bazzi
26-Nov-2013document.Save(this.Response, Server.MapPath("~/Users/Reports.pdf"));