Returning Multiple Files from MVC Action

Posted by Anuraj on Tuesday, June 24, 2014 Reading time :1 minute

.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", "");

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 :)

What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.

Similar Posts

Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon

BMC logoBuy me a coffee

Copyright © 2019 - Anuraj P. 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. Hosted with ❤ by GitHub