VVVV VVVV - 2 years ago 110
ASP.NET (C#) Question

Zip file is not getting downloaded using asp.net

I have a folder in which there are

3-4 pdf
files. SO on button click, I want to download PDF files as a
ZIP
file. For that I have write the below code

string strFilePath = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + SAP_ID + '_' + CANDIDATEID + "\\" + SAP_ID + '_' + CANDIDATEID + ".pdf");
string strDirectory = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + SAP_ID + '_' + CANDIDATEID);

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

if (Directory.Exists(strDirectory))
{
if (File.Exists(strFilePath + ".zip"))
{
var filestream = new System.IO.FileStream(strFilePath + ".zip", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
filestream.Close();
File.Delete(strFilePath + ".zip");
}
}

// ZipFile.CreateFromDirectory(strDirectory, strDirectory + ".zip");

var stream = new FileStream(strDirectory + ".zip", FileMode.Open);

result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(strDirectory + ".zip");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = stream.Length;


But on button click the ZIP is not getting downloaded and the browser just loads.

Please help me know what is the cause ?

Answer Source

You may have more luck with the Response.TransmitFile method, here is an example using the address of your zip file -

Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=file.zip");
Response.TransmitFile(strFilePath + ".zip");
Response.Flush();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download