26 March 2013

Dynamic text as file download in ASP.NET MVC

Recently I got a question to download a file in ASP.NET MVC. The CSV file dynamic content had to be built at runtime. 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 class HomeController : Controller
{
  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:

  1. First get the dynamic file content as string.
  2. Later Get the byte array using the required encoding. Here I have used ASCII encoding.
  3. 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);
Related links

Recently posted an article on implementing PRG pattern when doing HTTP POST request.