How to transfer large data from MVC3 correctly without using too much RAM?

I would like to use HttpResponse.OutputStream along with ContentResult so that I can Flush from time to time to avoid using too much RAM with .Net.

But all the MVC examples FileStreamResult, EmptyResult, FileResult, ActionResult, ContentResult show a code that receives all the data in memory and goes to one of them. Also, one post suggests returning EmptyResult along with using HttpResponse.OutputStream is a bad idea. How else can I do this in MVC?

What is the correct way to organize data output from big data (html or binary) from an MVC server?

Why is EmptyResult or ContentResult or FileStreamResult coming back a bad idea?

+8
stream model-view-controller asp.net-mvc ram asp.net-mvc-3
source share
1 answer

Would you like to use FileStreamResult if you already have a stream to work with. Many times you can only access the file, you need to create a stream and then output it to the client.

 System.IO.Stream iStream = null; // Buffer to read 10K bytes in chunk: byte[] buffer = new Byte[10000]; // Length of the file: int length; // Total bytes to read: long dataToRead; // Identify the file to download including its path. string filepath = "DownloadFileName"; // Identify the file name. string filename = System.IO.Path.GetFileName(filepath); try { // Open the file. iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read,System.IO.FileShare.Read); // Total bytes to read: dataToRead = iStream.Length; Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); // Read the bytes. while (dataToRead > 0) { // Verify that the client is connected. if (Response.IsClientConnected) { // Read the data in buffer. length = iStream.Read(buffer, 0, 10000); // Write the data to the current output stream. Response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output. Response.Flush(); buffer= new Byte[10000]; dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } } catch (Exception ex) { // Trap the error, if any. Response.Write("Error : " + ex.Message); } finally { if (iStream != null) { //Close the file. iStream.Close(); } Response.Close(); } 

Here's a Microsoft article explaining the code above.

+5
source share

All Articles