6

I just wanna ask how to generate or create textfile, becuase i want to display my data in the database as text.

im using c# in asp.net MVC 3

thank you very much! any answer will be apreciated.

2
  • Do you want to RETURN a text file to the user, or do you want to STORE a text file in a folder on the server? I don't understand "display my data in the database as text" Commented Feb 24, 2011 at 1:39
  • i just simply want to generate a textfile. like example after generating it , it will be put in the desktop or somewhere, i just want to generate a textfile with my database information in it thanks ! Commented Feb 24, 2011 at 1:41

2 Answers 2

14

If you just want to return some data from the database in a text file that will be downloaded to user's local computer, create an Action in your Controller like in this sample:

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 ")

I hope that helps!

Sign up to request clarification or add additional context in comments.

Comments

2

You can return plain text from an action by assembling a string and returning Content(textString, "text/plain").

5 Comments

a sample code will do please, im newbie, should i make a new class in the MODEL and put the codes there, and call it from the controller or what?
Because im thinking about getting the information from my database using repository then passing it to a string variable, so after passing it to a string variable i want to generate it as a textfile.
@sgolek: Create an action method in the controller that builds a string (you can use a StringBuilder in a loop), then write return Content(textString, "text/plain");.
Thanks SLaks !, i will create an action method now and post it in a minute so you can help me more, BTW. what should i put int the "text/plain" ? really noob here, really appreciate your help ! thanks a lot
"text/plain" is a MIME type. You should leave it as-is, or use "text/csv".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.