Click here to Skip to main content
15,886,067 members
Articles / General Programming / File
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
19 Jul 2013CPOL 80.9K   13   3
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:
 
C#
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:
 
C#
@Html.ActionLink("Download Text File", "CreateFile", "SomeController ")
 
And that's it!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
Coding is awesome!

Comments and Discussions

 
QuestionSave data from multiple text box mvc Pin
Member 146777558-Dec-19 19:40
Member 146777558-Dec-19 19:40 
QuestionQuery Pin
Antariksh Verma8-Aug-13 20:28
professionalAntariksh Verma8-Aug-13 20:28 
GeneralMy vote of 5 Pin
Christopher Sommers1-Aug-13 6:51
Christopher Sommers1-Aug-13 6:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.