Alex Rivera | Logout

Reading a binary file and using Response.BinaryWrite()

Asked 2009-05-11T15:35:11.290
27

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);
}
Edit
Report

1 Answer

16
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.Close();
        Response.End();

This works for us. We create PDFs from SQL Reporting Services.

answered 2009-05-11T15:55:52.553

Your Answer