2023
Download Files as Zip file in Asp.Net
64
Download Zip Files
For downloading the files in zip format we will use ZipArchieve class. For using this we have to install following nuget package.
Once you install this package you can go to controller and add following namespace
using System.IO; using System.IO.Compression;
Now, we have to add following code for download files as zip
public ActionResult DownloadFilesAsZip() { // Get the paths of the files to be included in the zip string[] filePaths = new string[] { Server.MapPath("~/Content/Screenshot_1.png"), Server.MapPath("~/Content/Screenshot_2.jpg"), Server.MapPath("~/Content/Screenshot_3.png") }; // Create a memory stream to store the zip file MemoryStream memoryStream = new MemoryStream(); using (ZipArchive zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { // Add each file to the zip archive foreach (string filePath in filePaths) { string fileName = Path.GetFileName(filePath); zipArchive.CreateEntryFromFile(filePath, fileName); } } // Set the position of the memory stream back to the beginning memoryStream.Position = 0; // Return the zip file for download return File(memoryStream, "application/zip", "Files.zip"); }
So, in the filepaths you can add any file paths that you want to add inside zip file.
Now we will add a link on the view to call this method.
@Html.ActionLink("Download Files as Zip", "DownloadFilesAsZip", "Home")
So, Now you can run the application and you have to click on the download button and it will download files as zip.
In the screenshots you can see the files getting downloaded as zip file.
In this example, the DownloadFilesAsZip action method takes an array of file paths and creates a zip archive using ZipArchive. Each file is added to the archive using CreateEntryFromFile
The resulting zip archive is then stored in a MemoryStream, and the position of the stream is set back to the beginning before returning the file using the File method. The File method takes the MemoryStream, the content type (in this case, "application/zip"), and the desired file name for the download.
So this is how we can Download Files as Zip file in Asp.Net.