Stream pdf to Response

D

DC

Hi,

I am trying to load a pdf file into a memorystream and upload this file
to the browser. However, wenn I run the attached code (the ftpStream is
a valid stream of the pdf file) I receive an "Application error" in the
Adobe Reader. I tried all the default encodings and the windows
encoding (below) with the same result.

TIA for any hint on what could be wrong here.

Regards
DC



ftpStream.Seek(0, SeekOrigin.Begin);

Response.ClearContent();
Response.ClearHeaders();
Response.BufferOutput = true;
Response.ContentType = "application/pdf";
byte[] buffer = new byte[8192];

int bytesRead = ftpStream.Read(buffer, 0, 8192);
while(bytesRead > 0)
{
char[] charArray =
Encoding.GetEncoding("windows-1252").GetChars(buffer, 0, bytesRead);
Response.Write(charArray, 0, charArray.Length);

bytesRead = ftpStream.Read(buffer, 0, 8192);
}
Response.End();
 
N

Nicholas Paldino [.NET/C# MVP]

DC,

Why are you changing the bytes from the stream into characters? There
is no reason to do this. Just send the bytes as they are to the client.
You are changing the format of the file into something that Acrobat can't
read (by converting to characters).

Also, you can't be sure that you actually read all of the bytes from the
stream. Jon Skeet has a good article on this:

http://www.pobox.com/~skeet/csharp/readbinary.html

Hope this helps.
 
R

Rowan R. Jugernauth

You might also want to have a look at the server.transfer() method.
It's pretty useful, you know.
 
D

DC

Thank you for the excellent advice Nicholas, I got it to work with
using byte arrays (see code below).

Regards
DC



byte[] buffer = new byte[8192];

ftpStream.Seek(0, SeekOrigin.Begin);

Response.ClearContent();
Response.ClearHeaders();
Response.BufferOutput = true;
Response.ContentType = "application/pdf";

int bytesRead = ftpStream.Read(buffer, 0, 8192);
while(bytesRead > 0)
{
byte[] buffer2 = new byte[bytesRead];
System.Buffer.BlockCopy(buffer, 0, buffer2, 0, bytesRead);

Response.BinaryWrite(buffer2);
Response.Flush();

bytesRead = ftpStream.Read(buffer, 0, 8192);
}
Response.End();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top