Mauro
Mauro

Reputation: 115

Why this action results an empty file on client side?

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

Upvotes: 1

Views: 3179

Answers (2)

jdehlin
jdehlin

Reputation: 11451

You can also use

stream.Seek(0, SeekOrigin.Begin);

Upvotes: 1

stevewarduk
stevewarduk

Reputation: 80

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.

Upvotes: 6

Related Questions