1
votes

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

2
I think the code is self-explanatory.Praveen
Maybe because you flush strem before return it?YD1m

2 Answers

6
votes

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
votes

You can also use

stream.Seek(0, SeekOrigin.Begin);