Reputation: 1992
I was trying to create and download a zip file from the different location using ZipArchive
class.
The files are located in the different file path. I want to create a zip file in c# in-memory object and then download it without saving the zip file in c# / MVC.
I have tried like this:
public void DownloadZipFromMultipleFile()
{
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
archive.CreateEntryFromFile(Server.MapPath("~/Content/appStyle.css"), "myStyle.css");
archive.CreateEntryFromFile(Server.MapPath("~/NewPath/myScript.js"), "script.js");
}
}
//archive.Save(Response.OutputStream);
}
I have successfully added files to archive
but not able to download the file as a zip file.
Upvotes: 1
Views: 1406
Reputation: 1992
As suggested by PapitoSh at comment section, I added few lines along with my existing codes and now it is working fine.
public void DownloadZipFromMultipleFile()
{
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
archive.CreateEntryFromFile(Server.MapPath("~/Content/appStyle.css"), "myStyle.css");
archive.CreateEntryFromFile(Server.MapPath("~/NewPath/myScript.js"), "script.js");
}
byte[] bytesInStream = memoryStream.ToArray(); // simpler way of converting to array
memoryStream.Close();
Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=name_you_file.zip");
Response.BinaryWrite(bytesInStream); Response.End();
}
//archive.Save(Response.OutputStream);
}
Upvotes: 1