MVC – Return a file download from an MVC controller

#1, Return a byte[] as a download

Use case; You have an in memory byte[] array containing something you want to offer as a a download. (For example an excel sheet)

string fileName = "something.xls";
return File(result, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);

#2 Return a text file as a download

Here we trick the browser to offering the file as a download by claiming the content is a binary stream. The used overload now takes the filehandle as input. As you can see, you are free to switch between in memory data and data store somewhere on disk.

return File(reportHandle, MediaTypeNames.Application.Octet, "repport.txt");

#3 Return a text file for viewing in your browser

Again, the MediaTypeName will determine how your browser ‘thinks’ of the file. If the mediatype is set to something your browser can handle itsself (directly such as text or html, of through a plugin such as pdf) your browser will attempt to display the content.

return File(reportHandle, MediaTypeNames.Text.