Generate text file via controller action in MVC => made easy!
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
Steps needed to do this are as given below:
Then you can create an
And that's it!
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:
- Create
string
with some data
- Convert it to an
Array
ofBytes
(byte[]
)
- Convert that
Array
ofBytes
toMemoryStream
- Return
FileStreamResult
by anAction
in yourController
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!