Sometimes, we will get requirements where we need to zip the files at runtime before sending it to the client side. For example, if our ASP.NET 4.5.2 application allows users to download multiple files at a time it will be better if we can zip it as a single file and make it available in a single download instead of downloading them individually. Doing this will give performance benefits and better user experience. Today, I wanted a simple way to create a backup of my posts, without resorting to FTP.  My solution is to create a URL that allows me to download the entire posts folder as a zip archive. To do the zipping, I used DotNetZip which is available as a nuget package and has a nice clean API.

Then in the Razor view (e.g. export.cshtml), the following code can be used to create a zip archive:
@using Ionic.Zip
@{
    Response.Clear();
    Response.BufferOutput = false; // for large files
    System.Web.HttpContext c= System.Web.HttpContext.Current;
    string archiveName= String.Format("archive-{0}.zip",
            DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
    Response.ContentType = "application/zip";
    Response.AddHeader("content-disposition", <br>             "filename=" + archiveName);
    var postsFolder = Server.MapPath("~/posts");
    using (ZipFile zip = new ZipFile())
    {
        zip.AddDirectory(postsFolder);
        zip.AddEntry("Readme.txt",
            String.Format("Archive created on {0}", DateTime.Now);
        zip.Save(Response.OutputStream);
    }
    Response.Close();   
}

It’s very straightforward, and I have also shown adding your own custom readme.txt from a string. If you’d rather add each file manually, just provide an enumeration of files to add to zip.AddFiles.

Finally, it would probably not be a great idea to let anyone call this, so you can protect it with a simple call to IsAuthenticated:
if (User.Identity.IsAuthenticated)