Because you're not flushing the StreamWriter
.
You're flushing the MemoryStream
, which is a no-op.
The StreamWriter class keeps a buffer internally, which you have not flushed, so the last few lines and/or characters will still be sitting in this buffer. If you click the link and look at the documentation you can see that the constructor documentation says such things as:
Initializes a new instance of the StreamWriter class for the specified stream by using UTF-8 encoding and the default buffer size.
(my emphasis)
Replace this:
ms.Flush();
with this:
sw.Flush();
Here's a simple LINQPad program that demonstrates:
void Main()
{
using (var ms = new MemoryStream())
using (var sw = new StreamWriter(ms, Encoding.UTF8))
{
for (int index = 1; index <= 200; index++)
sw.WriteLine("Line #" + index);
ms.Flush();
ms.Position = 0;
Encoding.UTF8.GetString(ms.ToArray()).Dump();
}
}
Output:
Line #1
Line #2
...
Line #196
(missing is line 197 through 200.)
After replacing ms.Flush();
with sw.Flush();
and running again the missing lines are present.