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.?
You may use the controller's
File
method to return a file, like:If the zip file is not required otherwise to be stored, it is unnecessary to write it into a file on the server:
First of all, consider a way without creating any files on the server's disk. Bad practise. I'd recommend creating a file and zipping it in memory instead. Hope, you'll find my example below useful.
Notes to the code above:
MemoryStream
instance requires checks that it's open, valid and etc. I omitted them. I'd rather passed a byte array of the file content instead of aMemoryStream
instance to make the code more robust, but it'd be too much for this example.Create a
GET
-only controller action that returns aFileResult
, like this:For those just wanting to return an existing Zip file from the App_Data folder (just dump in your zip files there), in the Home controller create this action method:
Get File is an extention method:
Home controller Index view looks like this:
The main index file action method:
Where GetFileInformation is an extension method:
just a fix to Klaus solution: (as I can not add comment I have to add another answer!)
The solution is great but for me it gave corrupted zip file and I realized that it is because of return is before finalizing zip object so it did not close zip and result in a corrupted zip.
so to fix we need to just move return line after using zip block so it works. the final result is :