Tuesday, 29 June 2010

Better know a framework: Flushing the System.IO.StreamWriter

I ran into an issue today where content that was being written to a Stream was being truncated when a large amount of text was being written. The code was something similar to:

using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream , Encoding.UTF8))
    DoSomethingWithTheStream(memoryStream );

The consuming method was then using the Stream but the end was truncated but if you take the following code from MSDN which writes to a FileStream using the StreamWriter it works as expected:

DirectoryInfo[] cDirs = new DirectoryInfo(@"c:\").GetDirectories();
using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))
    foreach (DirectoryInfo dir in cDirs)

After a bit of digging I realised that you need to call Flush() before using the Stream or turn on AutoFlush when using really long strings (or as good practice). The reason that the MSDN example worked is because it was writing to a FileStream in  a using block, when the Dispose method is called I presume it calls the flush method before destroying itself thus writing the rest of the content to the file. Whilst it would have been nice to see a comment to this affect in the StreamWriter remarks it does make sense.

No comments:

Post a Comment