快速创建文本文件,并在客户端下载/保存 [英] Creating a text file on the fly and have it download/save on client side

查看:82
本文介绍了快速创建文本文件,并在客户端下载/保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的ASP.NET Core 1.1,EF Core 1.1应用程序中,我们使用SQL Server中的一些数据填充了字符串,并希望即时创建一个文本文件,并希望用户从中保存/下载.客户端.

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();

如何在ASP.NET Core 1.1中实现?试图遵循 ASP.NET Core中的文件提供程序无济于事.

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

推荐答案

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")

或直接写响应:

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

可行的替代方法

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.

这篇关于快速创建文本文件,并在客户端下载/保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆