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

Create text file and download without saving on server in ASP.net Core MVC 2.1

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

Create text file and download

接受的答案使用:

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

我需要在 ASP.net Core 2.1 MVC 中执行此操作 - 虽然其中不知道 Response.OutputStream 是什么 - 我在 Google 上找不到任何帮助用那个,或者其他方法来做到这一点。

我该怎么做?谢谢

A little different way 但这似乎是你要找的东西

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

[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");
}

如果您只处理文本,则根本不需要做任何特殊的事情。就 return 个 ContentResult:

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

这对其他 "text" 内容类型同样适用,例如 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"header。或者,您可以 return Content 并手动设置此 header:

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

最后,如果您要在流中构建文本,则只需 return a FileStreamResult:

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

在下面的代码中使用 Response.OutputStream。但这在 asp.net 中完全有效,但 Response.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");
}
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");
}