Reputation: 252
I am having problems when I tried to run the following code from my asp.net page. The code is from another post (http://stackoverflow.com/questions/5828315/write-pdf-stream-to-response-stream). When the Test.pdf file is located in my local drive, I am not able to open the file when the open button on the dialog box is clicked. When, the save button is clicked, the file tries in as myAspPageName.pdf in "C:\Downloads" the operation goes on for ever without actually saving anything.
I am sure what I am doing wrong. Thanks for any help. Is there a better way of doing the same thing?
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();
}
}
}
Upvotes: 3
Views: 16316
Reputation: 24449
Consider using HttpResponse.TransmitFile
(ASP.NET >= 2.0), especially for large files because it writes the file without buffering it into server memory.
Also, make sure you always set the Response.ContentType
property to the appropriate MIME type or browsers will sometimes have trouble with downloading your files correctly, especially if you are writing the file from a handler:
Response.ContentType = "application/pdf";
Upvotes: 3
Reputation: 499302
You can use Response.WriteFile
instead of all the buffer work.
protected void Page_Load(object sender, EventArgs e)
{
Context.Response.WriteFile(@"C:\Downloads\Test.pdf");
}
Upvotes: 6