在 .NET Core 的 .txt 文件中创建没有文本的空文件

Empty File Created without text in .txt file in .NET Core

[HttpPost]
public FileResult DownloadFile(int id)
{
     using (MemoryStream ms = new MemoryStream())
       {
           var sw = new StreamWriter(ms);
           sw.Write("Hi");
           ms.Position = 0;
           return File(ms, "text/plain", "file.txt");
        }
}

结果:我得到一个空文本文件

Tried Code- var sw = new StreamWriter(ms,Encoding.UTF8,1024,true)

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

似乎没有任何效果。任何帮助,将不胜感激。谢谢。

您可以试试这个代码:

public FileResult DownloadFile(int id)
{
     using (MemoryStream ms = new MemoryStream())
        {
            var sw = new StreamWriter(ms);
            sw.Write("Hi");
            ms.Position = 0;
            sw.Flush();
            sw.Close();               
            return File(ms.GetBuffer(), "text/plain", "file.txt");
        }
}