DEV Community 👩‍💻👨‍💻

Cover image for Returning a Zip File from ASP.NET MVC Action - in Pure .NET
Alex Yumashev
Alex Yumashev

Posted on • Originally published at jitbit.com

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

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 libraries. And up until now that was the only solution.

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 zipArchiveEntry = archive.CreateEntry("image1.png", CompressionLevel.Fastest);
            using (var zipStream = zipArchiveEntry.Open())
            {
                zipStream.Write(bytes1, 0, bytes1.Length);
            }

            var zipArchiveEntry2 = archive.CreateEntry("image2.png", CompressionLevel.Fastest);
            using (var zipStream = zipArchiveEntry2.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.

Top comments (0)

Here is a post you might want to check out:

Regex for lazy developers

regex for lazy devs

Sorry for the callout 😆