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

4

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay