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);
1
  • 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. Commented Apr 4, 2012 at 14:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This should be marked as the answer. Link worked for me. Thanks.
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); 
}

3 Comments

I am getting a The process cannot access the file because it is being used by another process when trying this approach.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.