, , ,

How to create a zip file to download in asp.net – C# MVC

Posted by

To create a zip file and allow users to download it in an ASP.NET MVC application using C#, you can use the System.IO.Compression namespace. Here’s an example:

  1. Add the following namespaces in your controller:
using System.IO;
using System.IO.Compression;
  1. Create a method in your controller to generate and download the zip file:
public ActionResult DownloadZipFile()
{
    // Create a memory stream to hold the zip file contents
    using (MemoryStream memoryStream = new MemoryStream())
    {
        // Create a new ZIP archive
        using (ZipArchive zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        {
            // Add files to the zip archive
            // Replace with your logic to add files to the archive
            // You can loop through a list of file paths or use other criteria
            // For example, to add all files in a directory:
            string directoryPath = Server.MapPath("~/YourFilesDirectory");
            foreach (string filePath in Directory.GetFiles(directoryPath))
            {
                string fileName = Path.GetFileName(filePath);
                zipArchive.CreateEntryFromFile(filePath, fileName);
            }
        }

        // Set the memory stream position to the beginning
        memoryStream.Position = 0;

        // Return the zip file as a downloadable file
        return File(memoryStream, "application/zip", "download.zip");
    }
}
  1. Create a link or button in your view to trigger the download:
<a href="@Url.Action("DownloadZipFile", "YourController")">Download ZIP</a>

Make sure to replace “YourController” with the actual name of your controller.

When the user clicks on the “Download ZIP” link/button, it will trigger the DownloadZipFile action method in your controller. Inside the method, a zip file is created using the ZipArchive class, and the desired files are added to the archive. The resulting zip file is then returned to the user as a downloadable file using the File method.

Adjust the code according to your specific requirements, such as adding files from a specific directory or adding files based on certain criteria.