You need to use HttpResponse.TransmitFile
method. That will not buffer the file in memory but you still will get all the controls you need.
Filedownload with low memory even with big files
-
23-03-2022 - |
Question
I need to grant users access to restricted files. Were looking at using a generic webhandler for this operation.
The files can get quite big, 1,5GB atleast.
We need to serve these files with a little RAM/Memory usage as possible.
At the moment we are looking at this as the solution:
request.ContentType = "text/plain";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
int buffersize = 65536;
byte[] buffer = new byte[buffersize];
using (StreamReader reader = new StreamReader(filename))
{
int count = 0;
while (true)
{
int count = reader.Read(buffer, 0, buffersize);
dataStream.Write(buffer, 0, count);
if (count < buffersize) break;
}
}
Would this work for us?
Are there better solutions?
What do we need to watch out for?
Sharing the files directly through IIS is not an option. The handler needs to control who can access and who cannot.
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow