Programmatically create a Zip Archive file and send it as ActionResult using native ASP.NET MVC C#

ASP.NET MVC - Aggiungere uno o più percorsi di ricerca predefiniti per le View

If you're working with ASP.NET or ASP.NET Core and you need to create a zip file on-the-fly within your controller - for example to allow the user to download multiple files with a single request - you can easily do that using the ZipArchive class, introduced in Framework 4.5.

Here's a quick code sample using a MemoryStream and a couple of byte arrays representing two files:

Depending on your scenario you can use it inside a MVC Controller returning an ActionResult, / FileContentResult, persist the MemoryStream to disk, replace it with a FileStream and so on: in the above example I used the Controller.File method (from the System.Web.Mvc namespace) to return a FileContentResult object. If you're not using the MVC Framework you cannot do that, but you can still handle the MemoryStream in a different way, such as using Response.OutputStream or other standard techniques.

Needless to say, you can change the CompressionLevel to better suit your needs in terms of speed vs size. Also, if you need to phisically create the zip archive you can either persist the MemoryStream to disk or entirely replace it with a FileStream.

That's it for now: happy archiving!


About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.

View all posts by Ryan

Leave a Reply

Your email address will not be published. Required fields are marked *

The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.