Writers are like Streams

I recently saw some application code that misused XmlWriter and which happened not to work all the time as a result. What they were doing was using XmlWriter to write to an underlying stream and then flushing that stream without having flushed the writer.

Depending on the intervening code and the specific document being written in the application code, this might work if all of the content happens to have been committed to the stream prior to it being flushed. It's possible that they picked this error up by copying code from partial samples that don't show what to do with the writer after completing the content.

This example is an extreme demonstration of the problem that should result in the content never getting flushed through.

 using (FileStream stream = new FileStream("test.txt", FileMode.Create))
{
   XmlWriter writer = XmlDictionaryWriter.CreateTextWriter(stream);
   writer.WriteStartDocument();
   writer.WriteElementString("test", "value");
   writer.WriteEndDocument();
}

An intuition to use here is that an XmlWriter is like a wrapping stream, except that the XmlWriter streams XML content rather than bytes. That analogy might get you in the right frame of mind for remembering to flush or close the writer so that the data is available when you flush or close its underlying stream. Since XmlWriter is a disposable object, you can also use it with a using block to make this clear in the case where you don't have long-lived writers.

Next time: Getting Started Profiling Services