Recently I got a question to download a file in ASP.NET MVC. The CSV file dynamic content had to be built at run time. After bit of investigation found out how to download file such file in ASP.NET MVC
ASP.NET MVC action showing the download file code:
public ActionResult Download()
// Get the file content as string
string fileContent = GetCSVFileContent();
// Get the bytes for the dynamic string content
var byteArray = Encoding.ASCII.GetBytes(fileContent);
string fileName = "Download File in ASP.NET MVC
with dynamic content.csv";
return File(byteArray, "text/csv", fileName);
The steps followed are below:
- First get the dynamic file content as string.
- Later Get the byte array using the required encoding. Here I have used ASCII encoding.
Use the File() method in System.Web.Mvc.Controller class to send the array of bytes as file.
protected internal virtual FileStreamResult
File(Stream fileStream, string contentType, string fileDownloadName);
Recently posted an article on implementing PRG pattern when doing HTTP POST request.