Search code examples
c#fileasp.net-corestreamwritermemorystream

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

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.


Solution

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