Non-buffered Output in ASP.NET

Description

Most of the time, it makes sense to build a complete response and return it all at once. Sometimes, if you have a big result, like a large report, you’ll want to send the file a response a little at a time, to keep from storing a huge item in memory.

You can write to a file and then output that file in the response, or you can dynamically write and flush the response a little at a time, until the response completes.

public ActionResult GetFile() {
    string[] lines = { "line 1", "line 2", "line 3", "line 4" };
    Response.Clear();
    Response.ClearHeaders();
    Response.ContentType = "text/plain";
    Response.AddHeader("Content-disposition", "attachment;filename=somefile.txt");
    Response.Buffer = Response.BufferOutput = false;
    foreach (string line in lines) {
        Response.Write(line + "\r\n");
        Response.Flush();
    }
    HttpContext.ApplicationInstance.CompleteRequest();
    return null;
}

Find a strategy that makes sense - if you’re returning a text-based report, maybe flush every 100 or 1000 lines. You can always test various scenarios, and watch your memory usage in Windows and in the debugger to find the absolute best size.