Home > database >  Empty File Created without text in .txt file in .NET Core
Empty File Created without text in .txt file in .NET Core

Time:10-12

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

Result: I get an empty text file

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

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

Nothing seems to be working. Any help would be appreciated. Thank you.

CodePudding user response:

You can try this code:

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