back to Jitbit Blog home About this blog

Returning a Zip File from ASP.NET MVC Actions - in Pure .NET

by Alex Yumashev · Updated Sep 10 2019

If you search for "generate zip in ASP.NET/C#" you get tons of blog posts and StackOverflow answers suggesting DotNetZip, SharpZipLib and other 3rd party archiving libraries. And up until now that was the only solution - all because .NET had no built-in support for zip format.

But .NET Framework 4.5 and later (finally) includes native tools for working with Zip archives - ZipArchive class from the System.IO.Compressions namespace.

Here's an example of how you can dynamically generate a zip file inside an ASP.NET MVC action method (comes handy if you want to return multiple files within one response, for example):

public ActionResult GetFile()
{
    using (var ms = new MemoryStream())
    {
        using (var archive =
            new Compression.ZipArchive(ms, ZipArchiveMode.Create, true))
        {
            byte[] bytes1 = GetImage1Bytes();
            byte[] bytes2 = GetImage2Bytes();

            var zipEntry = archive.CreateEntry("image1.png",
                CompressionLevel.Fastest);
            using (var zipStream = zipEntry.Open())
            {
                zipStream.Write(bytes1, 0, bytes1.Length);
            }

            var zipEntry2 = archive.CreateEntry("image2.png",
                CompressionLevel.Fastest);
            using (var zipStream = zipEntry2.Open())
            {
                zipStream.Write(bytes2, 0, bytes2.Length);
            }
        }
        return File(ms.ToArray(), "application/zip", "Images.zip");
    }
}

I've just added two images files (in a form of byte arrays) into one zip-archive and returned it to the user. GetImage1Bytes and GetImage2Bytes are simply stubs for your code here. Nice and easy. But the best part - you're not using any external dependencies, all pure .NET.