1

Why this action results an empty file on client side ??


public FileResult download()
{

    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);

    FileStreamResult fs = new FileStreamResult(stream, "text/plain");
    fs.FileDownloadName = "file.txt";

    writer.WriteLine("this text is missing !!! :( ");

    writer.Flush();
    stream.Flush();

    return fs;                  
}

tereško
  • 58,060
  • 25
  • 98
  • 150
Mauro
  • 93
  • 1
  • 7

2 Answers2

6

It could be because the underlying stream (in your case a MemoryStream) is not positioned at the beginning when you return it to the client.

Try this just before the return statement:

stream.Position = 0

Also, these lines of code:

writer.Flush();
stream.Flush();

Are not required because the stream is Memory based. You only need those for disk or network streams where there could be bytes that still require writing.

1

You can also use

stream.Seek(0, SeekOrigin.Begin);
jdehlin
  • 10,909
  • 3
  • 22
  • 33