Download Files as Zip file in Asp.Net
Hello guys and welcome to Code2night! In today's article, we'll explore a common requirement in Asp.Net MVC where we often need to download all files as a zip. Fortunately, with the help of the ZipArchive class, accomplishing this task becomes a breeze. Throughout this article, we will guide you through the necessary steps to download files as a zip archive in your Asp.Net MVC application. So, let's dive right in and learn how to efficiently handle file downloads in zip format using the ZipArchive feature.
For downloading the files in zip format we will use ZipArchieve class. For using this we have to install the following Nuget package.
Once you install this package you can go to the controller and add the following namespace
using System.IO; using System.IO.Compression;
Now, we have to add the following code for download files as a 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 file paths, you can add any file paths that you want to add inside the 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 files.
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 a Zip file in Asp.Net.