I have an app that needs to read a PDF file from the file system and then write it out to the user. The PDF is 183KB and seems to work perfectly. When I use the code at the bottom the browser gets a file 224KB and I get a message from Acrobat Reader saying the file is damaged and cannot be repaired.
Here is my code (I've also tried using File.ReadAllBytes(), but I get the same thing):
using (FileStream fs = File.OpenRead(path))
{
int length = (int)fs.Length;
byte[] buffer;
using (BinaryReader br = new BinaryReader(fs))
{
buffer = br.ReadBytes(length);
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", Path.GetFileName(path)));
Response.ContentType = "application/" + Path.GetExtension(path).Substring(1);
Response.BinaryWrite(buffer);
}
In addition to Igor's Response.Close(), I would add a Response.Flush().
I also found it necessary to add the following:
If I didn't include this, my JPEG was corrupt and double the size in bytes.
But only if the handler was returning from an ASPX page. It seemed running from an ASHX this was not required.
Please read this before using Response.TransmitFile: http://improve.dk/blog/2008/03/29/response-transmitfile-close-will-kill-your-application
Maybe you are missing a Response.close to close de Binary Stream
Since you're sending the file directly from your filesystem with no intermediate processing, why not use
Response.TransmitFile
instead?(I suspect that your problem is caused by a missing
Response.End
, meaning that you're sending the rest of your page's content appended to the PDF data.)We've used this with a lot of success. WriteFile do to the download for you and a Flush / End at the end to send it all to the client.