1

While developing a web page that displays PDF, I am having trouble reading a PDF test file, of 86037 bytes, into a char[] array. That array is needed for output in HttpResponse.Write(char[], 0, nrbytes) . My code works fine with HttpResponse.WriteFile(filename), so all http headers must be OK.

When I try:

byte[] bytPdf = File.ReadAllBytes(FileName);
string strPdf = System.Text.Encoding.ASCII.GetString(bytPdf);
char[] chrPdf = strPdf.ToCharArray();
response.Write(chrPdf , 0 , chrPdf.Length);//L=86027, OK

the browser shows two empty pages: two is correct, but the pdf has filled pages. When I try:

string strPdf = File.ReadAllText(FileName);
response.Write(strPdf.ToCharArray(), 0, strPdf.Length);//L=85387, wrong

the string is missing bytes, probably because of some binary bytes mistaken for end-of-file. The browser keeps waiting for data.

I feel that I am not getting the entire PDF content correctly in the string or char[].

Alternatively, is there a method to send a byte[] to the HTTP output, instead of char[]?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Roland
  • 4,619
  • 7
  • 49
  • 81
  • 2
    `Response.BinaryWrite()`: http://stackoverflow.com/questions/848679/reading-a-binary-file-and-using-response-binarywrite – Alex K. Feb 17 '14 at 17:25
  • Great, that worked! Too bad that method wasn't closer in name to .Write, .WriteFile, or an overload of .Write(char[]) :-( – Roland Feb 17 '14 at 17:33
  • 1
    As an aside... Never ever try to treat binary file formats as character data. You will most likely break them. – mkl Feb 17 '14 at 18:15
  • Right, that's what happened. The binary data in the PDF may contain bytes that can be interpreted as an End-Of-File or End-Of-Transmission character. All data transmitted after such byte will not be received by the browser, which either will wait forever, or show an error message like "file damaged". By using method `response.BinaryWrite(bytes[])`, such bytes can be safely transmitted, unlike `response.Write(char[])`. – Roland Feb 18 '14 at 11:06

0 Answers0