Data is truncated from memory stream while reading

I have the following code that uses StreamWriter to write to a MemoryStream . However, when I try to read the stream, I get truncated data:

 using(var outStream = new MemoryStream()) using (var outWriter = new StreamWriter(outStream)) { // my operation that 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 toward the end. However, I know that the data gets into the stream, because if I try to write a file instead of a MemoryStream , I get all the contents. For example, this code writes all the contents to a file:

 using (var outWriter = new StreamWriter(@"C:\temp\test.out")) { // my operation that writing data to the stream } 
+4
source share
1 answer

You do not flush the writer - washing outStream meaningless, since there is nothing to flush. You must have:

 outWriter.Flush(); 

before rewinding. Your later code proves that the data reaches the writer, not the stream.

Alternatively, just use StringWriter from the beginning ... which is much easier to create a TextWriter and then get the text written on it later.

+8
source

Source: https://habr.com/ru/post/1485070/


All Articles