Writing a PDF stream to a response stream

I am having problems when I tried to run the following code from my asp.net page. Code from another post (http://stackoverflow.com/questions/5828315/write-pdf-stream-to-response-stream). When the Test.pdf file is on my local drive, I cannot open the file when the open button in the dialog box is clicked. When the save button is pressed, the file tries as myAspPageName.pdf in "C: \ Downloads", the operation continues forever without saving anything.

I am sure that I am doing wrong. Thanks for any help. Is there a better way to do the same?

protected void Page_Load(object sender, EventArgs e) 
{         
    Context.Response.Buffer = false;         
    FileStream inStr = null;         
    byte[] buffer = new byte[1024];         
    long byteCount; inStr = File.OpenRead(@"C:\Downloads\Test.pdf");         
    while ((byteCount = inStr.Read(buffer, 0, buffer.Length)) > 0) 
    {    
        if (Context.Response.IsClientConnected) 
        { 
            Context.Response.ContentType = "application/pdf";
            Context.Response.OutputStream.Write(buffer, 0, buffer.Length);
            Context.Response.Flush();             
        }        
    }     
} 
+3
source share
2 answers

You can use Response.WriteFileinstead of working with a buffer.

protected void Page_Load(object sender, EventArgs e) 
{         
    Context.Response.WriteFile(@"C:\Downloads\Test.pdf"); 
}
+6
source

HttpResponse.TransmitFile (ASP.NET >= 2.0), , .

, , Response.ContentType MIME , :

Response.ContentType = "application/pdf";
+3

All Articles