Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a binary file and using Response.BinaryWrite()

Tags:

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); } 
like image 317
jhunter Avatar asked May 11 '09 15:05

jhunter


People also ask

What does Response BinaryWrite do?

The BinaryWrite method writes the specified information to the current HTTP output without any character conversion. This method is useful for writing nonstring information, such as binary data required by a custom application.

Which method is used to read data from a binary file?

The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing a FileStream object to its constructor.


1 Answers

Try adding

Response.End();

after the call to Response.BinaryWrite().

You may inadvertently be sending other content back after Response.BinaryWrite which may confuse the browser. Response.End will ensure that that the browser only gets what you really intend.

like image 113
BarneyHDog Avatar answered Sep 22 '22 07:09

BarneyHDog