Downloading of zip file through ASP.NET MVC using DotNetZip

user2801336 picture user2801336 · Apr 28, 2015 · Viewed 46.2k times · Source

I have created a text file in a folder and zipped that folder and saved @same location for test purpose. I wanted to download that zip file directly on user machine after it is created. I am using dotnetzip library and have done following:

Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=" + "sample.zip");
using (ZipFile zip = new ZipFile())
{
    zip.AddDirectory(Server.MapPath("~/Directories/hello"));
    zip.Save(Server.MapPath("~/Directories/hello/sample.zip"));
}

Can someone please suggest how the zip file can be downloaded at user's end.?

Answer

mcserep picture mcserep · Apr 28, 2015

You may use the controller's File method to return a file, like:

public ActionResult Download()
{
    using (ZipFile zip = new ZipFile())
    {
        zip.AddDirectory(Server.MapPath("~/Directories/hello"));
        zip.Save(Server.MapPath("~/Directories/hello/sample.zip"));
        return File(Server.MapPath("~/Directories/hello/sample.zip"), 
                                   "application/zip", "sample.zip");
    }
}

If the zip file is not required otherwise to be stored, it is unnecessary to write it into a file on the server:

public ActionResult Download()
{
    using (ZipFile zip = new ZipFile())
    {
        zip.AddDirectory(Server.MapPath("~/Directories/hello"));

        MemoryStream output = new MemoryStream();
        zip.Save(output);
        return File(output.ToArray(), "application/zip", "sample.zip");
    }  
}