Download Dynamically Generated File in ASP.NET MVC

asp.net-mvc

Solution

Here's an overly simplified version of the code I ended up using. It meets my needs.

[HttpGet]
public ActionResult GetFile()
{
    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=myfile.csv");
    Response.ContentType = "text/csv";

    // Write all my data
    Response.Write(...);
    Response.End();

    // Not sure what else to do here
    return Content(String.Empty);
}

Problem

I need to implement a file download in ASP.NET MVC. Searching the Web, I found code like this: ``` public ActionResult GetFile() { return File(filename, "text/csv", Server.UrlEncode(filename)); } ``` That's nice, but I want to create the contents of this file dynamically. I realize I could dynamically create the file, and then use the syntax above to download that file. But wouldn't it be more efficient if I could simply write my contents directly to the response? Is this possible in MVC?

Original source

Related problems