Reputation:
I am having some issues with trying to create a file from a string and download it in ASP.NET Core.
What I am trying to do is that when a user presses a button I fetch some data as a string and create a file from it. In addition I would like to download this file to the pc. I have not been able to figure out a solution that works and so far this is the closest I have gotten:
public async Task<FileStreamResult> DownloadFile()
{
string s = "Some string with data";
MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
await tw.WriteAsync(s);
tw.Flush();
return File(ms, "application/force-download", "readme.txt");
}
The problem is that this does not work for some reason, the MemoryStream does not seem to stream the bytes of data to the file.
Upvotes: 1
Views: 1020
Reputation: 1540
Convert memory stream to byte[]
:
public async Task<FileStreamResult> DownloadFile()
{
string s = "Some string with data";
MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
await tw.WriteAsync(s);
tw.Flush();
byte[] bytes = ms.ToArray();
ms.Close();
return File(bytes, "application/force-download", "readme.txt");
}
Upvotes: 1