Create text file and download without saving on server in ASP.net Core MVC 2.1

niico picture niico · Nov 27, 2018 · Viewed 8.5k times · Source

I've found a way to create a text file then instantly download it in the browser without writing it to the server in regular ASP.net:

Create text file and download

The accepted answer uses:

using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8)) {
  writer.Write("This is the content");
}

I need to do this in ASP.net Core 2.1 MVC - though in that doesn't know what Response.OutputStream is - and I can't find anything on Google to help with that, or other ways to do this.

How can I do this? Thanks.

Answer

Chris Pratt picture Chris Pratt · Nov 27, 2018

If you're dealing with just text, you don't need to do anything special at all. Just return a ContentResult:

return Content("This is some text.", "text/plain");

This works the same for other "text" content types, like CSV:

return Content("foo,bar,baz", "text/csv");

If you're trying to force a download, you can utilize FileResult and simply pass the byte[]:

return File(Encoding.UTF8.GetBytes(text), "text/plain", "foo.txt");

The filename param prompts a Content-Disposition: attachment; filename="foo.txt" header. Alternatively, you can return Content and just set this header manually:

Response.Headers.Add("Content-Disposition", "attachment; filename=\"foo.txt\"");
return Content(text, "text/plain");

Finally, if you're building the text in a stream, then simply return a FileStreamResult:

return File(stream, "text/plain", "foo.txt");