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:
- Create
string
with some data
- Convert it to an
Array
of Bytes
(byte[]
)
- Convert that
Array
of Bytes
to MemoryStream
- 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 {
public FileStreamResult CreateFile() {
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!