Friday 20 June 2014

How to Zip a Folder with ASP.NET Web Pages

Since I’m basing my new blog on MiniBlog, all my posts are stored as XML files in a posts folder. 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", 
"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(); }

As you can see, it’s very straightforward, and I’ve 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)

No comments: