3

I have an Action which is responsible for pulling some data out from the database and returning it as a CSV file.

I know I could do it by returning a massive string but I was thinking if there is a clean and efficient way that could be used to return a CSV file through an MVC controller action.

tereško
  • 58,060
  • 25
  • 98
  • 150
Whiz Kid
  • 31
  • 1
  • 3
  • Or use the FileStreamResult object instead of ActionResult like [this stack overflow post][1] [1]: http://stackoverflow.com/questions/1375486/how-to-create-file-and-return-it-via-fileresult-in-asp-net-mvc – leon.io May 21 '12 at 15:24

1 Answers1

6

The FileResult is what you are looking for:

http://msdn.microsoft.com/en-us/library/system.web.mvc.fileresult.aspx

public ActionResult GetFile()
{
    var stream = new StreamReader("thefilepath.txt");
    return File(stream.ReadToEnd(), "text/plain");
}

Best regards

Oscar
  • 13,594
  • 8
  • 47
  • 75
  • Thanks for your reply. I came across a similar solution but some people argued that this will create a new file on the server every time – Whiz Kid May 21 '12 at 15:45
  • 2
    I don't see where you are creating a new file in the server.. Your're just reading the file into an stream, not creating anything else.. If unsure, use MemoryStream instead of StreamReader. – Oscar May 21 '12 at 15:55