If I have a pdf file as a Stream, how can I write it to the response output stream?
Asked
Active
Viewed 7.8k times
5 Answers
22
Since you are using MVC, the best way is to use FileStreamResult
:
return new FileStreamResult(stream, "application/pdf")
{
FileDownloadName = "file.pdf"
};
Playing with Response.Write
or Response.OutputStream
from your controller is non-idiomatic and there's no reason to write your own ActionResult when one already exists.
12
One way to do it is as follows:
//assuming you have your FileStream handle already - named fs
byte[] buffer = new byte[4096];
long count = 0;
while ((count = fs.Read(buffer, 0, buffer.Length)) > 0)
{
response.OutputStream.Write(buffer, 0, count);
response.Flush();
}
You can also use GZIP compression to speed the transfer of the file to the client (less bytes streamed).

ljkyser
- 999
- 5
- 9
-
2It's better to just set up compression of dynamic content in IIS7 config so it happens across the board. – Talljoe Apr 29 '11 at 05:54
-
@Talljoe - agreed I'd set it up that way as well, I should have been more clear – ljkyser Apr 29 '11 at 05:56
-
Eh... does this even work? System.IO.Stream.Write(byte[], int, int) you have count as a long = no workie. – Paul Zahra Mar 13 '18 at 11:30
7
In asp.net this is the way to download a pdf file
Dim MyFileStream As FileStream
Dim FileSize As Long
MyFileStream = New FileStream(filePath, FileMode.Open)
FileSize = MyFileStream.Length
Dim Buffer(CInt(FileSize)) As Byte
MyFileStream.Read(Buffer, 0, CInt(FileSize))
MyFileStream.Close()
Response.ContentType = "application/pdf"
Response.OutputStream.Write(Buffer, 0, FileSize)
Response.Flush()
Response.Close()

Abdul Saboor
- 4,079
- 2
- 33
- 25
-
3I would like this answer a lot more if it was written in c# like the question asks – JSON Aug 10 '16 at 20:26
-
1Downvote because FileStream is not automatically disposed (try/finally or using). – arni Dec 01 '17 at 17:16
4
The HTTP Response is a stream exposed to you through the HttpContext.Response.OutputStream
property, so if you have the PDF file in a stream you can simply copy the data from one stream to the other:
CopyStream(pdfStream, response.OutputStream);
For an implementation of CopyStream
see Best way to copy between two Stream instances - C#
-2
Please try this one:
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:\Users\Downloads\sample.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();
}
}
}

Peyton Crow
- 872
- 4
- 9
-
Why the length of byte array is 1024? What if its size is more than you defined ? – Frank Myat Thu Aug 26 '14 at 08:12