Last post Nov 19, 2020 11:58 AM by PatriceSc
Nov 19, 2020 08:46 AM|Jagan Mohan|LINK
I need to display a pdf file in an ASP.NET Web Forms 4 application through an ascx user control. I'm using the below code for reading the pdf file as byte array and then write the byte array to the Response directly.
var pdfBytes = File.ReadAllBytes(filePath);
I tried using
But its performance is not satisfying. In case of very large pdf files it's not performing well even though the pdf files were generated with Fast Web View option enabled. Can someone suggest a better solution for this?
Nov 19, 2020 11:58 AM|PatriceSc|LINK
So the first approach is really quicker but the problem is memory consumption?
I see also
https://docs.microsoft.com/en-us/dotnet/api/system.web.httpresponse.outputstream?view=netframework-4.8 but I never gave this a close look from a performance point of view.
A quick benchmark could help (make sure cachiing won't interfere). At worst the source code should be available at github to better understand what happens behind the scene. What is the size of a "very large" PDF file?
You could use your own TransmitBinaryFile extension method and change it's implementation based on benchmark findings.
Edit: I see for example
https://blogs.objectsharp.com/post/2005/03/28/Optimizing-the-Downloading-of-Large-Files-in-ASPNET.aspx but it's quite old, not very clear about how the approach relates to the various option found in the article and it's likely often best to test your own
Edit 2: for now my understanding is that the best option according to this article might be (but they don't even show which buffer size they used):
using( Stream s = new FileStream( fileName, FileMode.Open,
FileAccess.Read, FileShare.Read, bufferSize ) )
byte buffer = new byte[bufferSize];
int count = 0;
int offset = 0;
while( (count = s.Read( buffer, offset, buffer.Length ) ) > 0 )
ctx.Response.OutputStream.Write( buffer, offset, count );
You'll likely have to do your own testing.