Ajit Goel
Ajit Goel

Reputation: 4418

c#- Corrupt file when writing to Response

I am trying to write a file to the output response stream using ASP.Net. When I download the file, I get a Errors were found opening .zip file. You can extract files from this archive, but other programs may not be able to open it. Do you want to try fixing the problems? error. I am however able to cancel this and open the zip file correctly.

What could I be doing wrong?

ASP.Net\C# code:

var pathToFile = "c:\abc.zip";
string fileName = Path.GetFileName(pathToFile);
byte[] buffer;
using (var fileStream = new FileStream(pathToFile, Filemode.open))
{
  buffer = new byte[fileStream. Length];
  fileStream.Read(buffer, 0, (int)fileStream.Length);
}
Response.Clear();
Response.Buffer = true;
Response.AppendHeader("content-disposition", string.Format(@"attachment; filename={0}.zip", filename));
Response.ContentType = "application/zip";
Response.AppendHeader("content-length", buffer.Length.ToString());
Response.WriteFile(pathToFile);

Upvotes: 0

Views: 588

Answers (1)

Li-Jyu Gao
Li-Jyu Gao

Reputation: 940

If you want to use buffer and write file to user, do not use Response.WriteFile.

Change to Response.OutputStream.Write, and modify your codes, like this:

var pathToFile = "c:\abc.zip";
string fileName = Path.GetFileName(pathToFile);
byte[] buffer = new byte[0];
using (var fileStream = new FileStream(pathToFile, FileMode.Open, FileAccess.Read))
{
  buffer = new byte[fileStream.Length];
  fileStream.Read(buffer, 0, buffer.Length);
}
Response.Clear();
Response.AppendHeader("content-disposition", string.Format(@"attachment; filename={0}", filename));
Response.ContentType = "application/zip";
Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.Flush();
Response.End();

Upvotes: 2

Related Questions