在ASP.net Core MVC 2.1中创建文本文件并下载,而不保存在服务器上



我找到了一种方法,可以创建一个文本文件,然后立即在浏览器中下载,而无需将其写入常规ASP.net中的服务器:

创建文本文件并下载

接受的答案使用:

using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8)) {
writer.Write("This is the content");
}

我需要在ASP.net Core 2.1 MVC中做这件事——尽管在那里不知道什么是响应。OutputStream是——我在谷歌上找不到任何帮助,也找不到其他方法。

我该怎么做?谢谢

如果你只处理文本,你根本不需要做任何特别的事情。只需返回一个ContentResult:

return Content("This is some text.", "text/plain");

这对其他"文本"内容类型也是一样的,比如CSV:

return Content("foo,bar,baz", "text/csv");

如果你试图强制下载,你可以使用FileResult,只需通过byte[]:

return File(Encoding.UTF8.GetBytes(text), "text/plain", "foo.txt");

filename参数提示Content-Disposition: attachment; filename="foo.txt"标头。或者,您可以返回Content并手动设置此标头:

Response.Headers.Add("Content-Disposition", "attachment; filename="foo.txt"");
return Content(text, "text/plain");

最后,如果您在流中构建文本,那么只需返回一个FileStreamResult:

return File(stream, "text/plain", "foo.txt");

在下面的代码中,您使用Response。OutputStream。但是这在asp.net中是有效的,但是响应。OutputStream在asp.net核心中引发错误。

using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8)) {
writer.Write("This is the content");
}

所以,使用以下代码下载asp.net核心中的文件。

using (MemoryStream stream = new MemoryStream())
{
StreamWriter objstreamwriter = new StreamWriter(stream);
objstreamwriter.Write("This is the content");
objstreamwriter.Flush();
objstreamwriter.Close(); 
return File(stream.ToArray(), "text/plain", "file.txt");
}

有点不同,但这似乎是您想要的

编辑:修复文件末尾的尾随零

[HttpGet]
[Route("testfile")]
public ActionResult TestFile()
{
MemoryStream memoryStream = new MemoryStream();
TextWriter tw = new StreamWriter(memoryStream);
tw.WriteLine("Hello World");
tw.Flush();
var length = memoryStream.Length;
tw.Close();
var toWrite = new byte[length];
Array.Copy(memoryStream.GetBuffer(), 0, toWrite, 0, length);
return File(toWrite, "text/plain", "file.txt");
}

旧答案(尾随零问题(

[HttpGet]
[Route("testfile")]
public ActionResult GetTestFile() {
MemoryStream memoryStream = new MemoryStream();
TextWriter tw = new StreamWriter(memoryStream);
tw.WriteLine("Hello World");
tw.Flush();
tw.Close();
return File(memoryStream.GetBuffer(), "text/plain", "file.txt");
}
public ActionResult Create(Information information)
{
var byteArray = Encoding.ASCII.GetBytes(information.FirstName + "" + information.Surname + "" + information.DOB + "" + information.Email + " " + information.Tel);
var stream = new MemoryStream(byteArray);
return File(stream, "text/plain", "your_file_name.txt");
}

最新更新