Returning Multiple Files from MVC Action

June 24, 2014 by Anuraj

.Net ASP.Net ASP.Net MVC CodeProject

Today I faced an issue with ASP.Net MVC, I have to download multiple files as a compressed (zip) file. Initially I thought of using third party component like DotNetZip. Later I used ZipArchive class, which comes with .Net Framework 4.5.

And here is the controller action.

public ActionResult Download()
{
    using (var memoryStream = new MemoryStream())
    {
        using (var ziparchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        {
            for (int i = 0; i < 10; i++)
            {
                var readmeEntry = ziparchive.CreateEntry(string.Format("File_{0}.txt", i));
                using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                {
                    writer.WriteLine(string.Format("File_{0} - Contents", i));
                }
            }
            ziparchive.CreateEntryFromFile(Server.MapPath("~/Files/file1.txt"), "file1.txt");
            ziparchive.CreateEntryFromFile(Server.MapPath("~/Files/file2.txt"), "file2.txt");
            ziparchive.CreateEntryFromFile(Server.MapPath("~/Files/file3.txt"), "file3.txt");
        }

        return File(memoryStream.ToArray(), "application/zip", "Attachments.zip");
    }
}

In this implementation I creating text file on the fly and I am reading and using existing files as well.

Note: Following namespaces are required.

using System.IO;
using System.IO.Compression;

You may need to add reference of System.IO.Compression.FileSystem namespace explicitly, without this assembly reference visual studio will not recognize ZipArchive class.

Happy Coding :)

Support My Work

If you find my content helpful, consider supporting my work. Your support helps me continue creating valuable resources for the community.

Share this article

Found this useful? Share it with your network!

Copyright © 2025 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub