Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

how to create a text file in asp.net MVC3 using c#

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...