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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With