Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data is truncated from memory stream when reading

I have the following code that is using StreamWriter to write to a MemoryStream. However, when I try to read back the stream I am getting truncated data:

using(var outStream = new MemoryStream())
using (var outWriter = new StreamWriter(outStream))
{
    // my operation that's writing data to the stream

    var outReader = new StreamReader(outStream);
    outStream.Flush();
    outStream.Position = 0;
    return outReader.ReadToEnd();

}

This returns most of the data, but truncates near the end. However, I know the data is getting to the stream because if I try to write to a file instead of a MemoryStream I get the entire contents. For example, this code writes the entire contents to file:

using (var outWriter = new StreamWriter(@"C:\temp\test.out"))
{
    // my operation that's writing data to the stream
}
like image 659
Kyle Avatar asked Jun 07 '13 15:06

Kyle


1 Answers

You're not flushing the writer - flushing outStream is pointless, as there's nothing to flush it to. You should have:

outWriter.Flush();

before you rewind. Your later code proves that the data reaches the writer - not the stream.

Alternatively, just use StringWriter from the start... that's a much simpler way of creating a TextWriter and then getting the text written to it later on.

like image 69
Jon Skeet Avatar answered Sep 22 '22 17:09

Jon Skeet