Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 19 Jul 2013
Rate this:
Please Sign up or sign in to vote.
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!

License

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

Share

About the Author

Mikhail-T
Web Developer
United States United States
MVC, .NET, AngularJS, JQuery, and POST/GET - all are my good friends!

Comments and Discussions

 
QuestionQuery PinprofessionalAntariksh Verma8-Aug-13 20:28 
GeneralMy vote of 5 PinmemberChristopher Sommers1-Aug-13 6:51 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 19 Jul 2013
Article Copyright 2012 by Mikhail-T
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid