0

I have a large zip file (500MB or greater) that I am reading into a MemoryStream and return as a FileStreamResult. However, I am getting a OutOfMemory Exception for files over 200MB. Within my Action I have the following code:

MemoryStream outputStream = new MemoryStream();
using (var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
   //Response.BufferOutput = false;   // to prevent buffering
   byte[] buffer = new byte[1024];
   int bytesRead = 0;
   while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
   {
      outputStream.Write(buffer, 0, bytesRead);
   }
}

outputStream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(outputStream, content_type);
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
user327999
  • 443
  • 1
  • 9
  • 21
  • I do not want to use ReadAllBytes because of 2GB limit and also because of the memory issues when reading entire file into memory at once. – user327999 Apr 04 '12 at 14:25

2 Answers2

2

You could try the solution proposed on this page:

OutOfMemoryException when sending a big file 500mb using filestream

It shows how to read the file into an IStream and send the Response.

Community
  • 1
  • 1
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
2

If you read the file into a MemoryStream you still need to allocate the memory for the whole file, as internally the MemoryStream is nothing else than a byte array.

So currently you are reading your file into a large memory buffer using a smaller intermediate (also in memory) buffer.

Why not forward the file stream directly to the FileStreamResult?

using (var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
    return new FileStreamResult(fs, content_type); 
}
Fionn
  • 10,975
  • 11
  • 54
  • 84
  • I am getting a The process cannot access the file because it is being used by another process when trying this approach. – user327999 Apr 04 '12 at 14:59
  • Sorry that the answer is so late, didn't notice it earlier. This should help: new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read). It allows multiple opening of the file as long as it is read access. – Fionn Apr 19 '12 at 15:27
  • Couldn't get this to work. If I remove the using's it gives out of memory exception. If it include the Using my mvc app is 302 re-directing to our error page...Not sure why. – RayLoveless Aug 26 '16 at 19:59