Click here to Skip to main content
13,141,429 members (23,933 online)
Click here to Skip to main content
Add your own
alternative version


13 bookmarked
Posted 17 Jan 2012

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!


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


About the Author

Web Developer
United States United States
Coding is awesome!

You may also be interested in...


Comments and Discussions

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
memberChristopher 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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170915.1 | Last Updated 19 Jul 2013
Article Copyright 2012 by Mikhail-T
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid