Write PDF stream to response stream

If I have a pdf file as a Stream, how can I write it to the response output stream?


Solution 1:

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.

Solution 2:

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).