Creating a text file on the fly and have it download/save on client side

[亡魂溺海] 提交于 2019-12-08 01:08:51

问题


In our ASP.NET Core 1.1, EF Core 1.1 app we have populated a string with some data from SQL Server and would like to have a text file created out of it on the fly and have a user save/download from the client side.

In old days we used to do it as follows:

List<string> stringList = GetListOfStrings();

MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);

foreach (string s in stringList) {
    tw.WriteLine(s);
}
tw.Flush();
byte[] bytes = ms.ToArray();
ms.Close();

Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=myFile.txt");
Response.BinaryWrite(bytes);
Response.End();

How can that be achieved in ASP.NET Core 1.1? Tried to follow File Providers in ASP.NET Core to no avail.


回答1:


MemoryReader mr = new MemoryStream();
TextWriter tw = new StreamWriter(mr);

foreach (string s in stringList) {
    tw.WriteLine(s);
}
tw.Flush();

return File(mr, "application/force-download", "myFile.txt")

Or directly write to the response:

HttpContext.Response.Body.WriteAsync(...);

Also viable alternative

TextWriter tw = new StreamWriter(HttpContext.Response.Body);

so you can directly write to the output string, without any additional memory usage. But you shouldn't close it, since it's the connection to the browser and may be needed further up in the pipeline.



来源:https://stackoverflow.com/questions/44294369/creating-a-text-file-on-the-fly-and-have-it-download-save-on-client-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!