ASP.NET MVC and Ionic.Zip

March 22, 2010 at 10:19 AM | categories: Programming | View Comments

I wanted to stream a dynamically generated Zip file in a ASP.NET MVC site. Ionic.Zip looked like the best option for Zip library. The Create a downloadable zip within ASP.NET example looked pretty close to what I needed, but I wanted to have a suitable ActionResult class to use in my controller. Here is what I came up with:

    /// <summary>
    /// A content result which can accepts a DotNetZip ZipFile object to write to the output stream
    /// </summary>
    public class ZipFileResult : ActionResult
    {

        public ZipFile zip {get;set;}
        public string filename {get; set;}

        public ZipFileResult(ZipFile zip)
        {
            this.zip = zip;
            this.filename = null;
        }
        public ZipFileResult(ZipFile zip, string filename)
        {
            this.zip = zip;
            this.filename = filename;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var Response = context.HttpContext.Response;

            Response.ContentType = "application/zip";
            Response.AddHeader("Content-Disposition", "attachment;" + (string.IsNullOrEmpty(filename) ? "" : "filename=" + filename));


            zip.Save(Response.OutputStream);

            Response.End();
        }
    }

The example noted above becomes:

public class MyZipFileController : Controller
{

    public ActionResult Index()
    {
        string ReadmeText= "This is a zip file dynamically generated at " + System.DateTime.Now.ToString("G");
        string filename = System.IO.Path.GetFileName(ListOfFiles.SelectedItem.Text) + ".zip";

        ZipFile zip = new ZipFile();
        zip.AddFile(ListOfFiles.SelectedItem.Text, "files");
        zip.AddEntry("Readme.txt", "", ReadmeText);
        return new ZipFileResult(zip, filename);
    }
}
blog comments powered by Disqus