65.9K
CodeProject is changing. Read more.
Home

Generate text file via controller action in MVC => made easy!

starIconstarIconstarIconstarIconstarIcon

5.00/5 (7 votes)

Jan 17, 2012

CPOL
viewsIcon

82270

How to convert string to text file and return it back to user as a result of a controller action

This is a very simple solution if you just need to convert some string variable (e.g. with some database data) into the text file, and then download it to your local computer.
 
Steps needed to do this are as given below:
  1. Create string with some data
  2. Convert it to an Array of Bytes (byte[])
  3. Convert that Array of Bytes to MemoryStream
  4. Return FileStreamResult by an Action in your Controller
So, to get this working, just setup your Controller and Action like in the sample below:
 
using System.IO;
using System.Text;      
 
public class SomeController {
 
    // this action will create text file 'your_file_name.txt' with data from
    // string variable 'string_with_your_data', which will be downloaded by
    // your browser
    public FileStreamResult CreateFile() {
        //todo: add some data from your database into that string:
        var string_with_your_data = "";
 
        var byteArray = Encoding.ASCII.GetBytes(string_with_your_data);
        var stream = new MemoryStream(byteArray);
 
        return File(stream, "text/plain", "your_file_name.txt");   
    }
}
 
Then you can create an ActionLink to that Action on your View which will trigger file download:
 
@Html.ActionLink("Download Text File", "CreateFile", "SomeController ")
 
And that's it!