I've looked around on the net but didn't find anything about what seems like a bug in XmlWriter to me. The thing is, in .net 2.0, instead of doing a new XmlWriter(), there is now a static XmlWriter.Create method, with a number of overloads. That stated, can you spot anything wrong with this code:
XmlWriter writer = XmlWriter.Create(new FileStream("test.xml", FileMode.Create));
// do some stuff
writer.Close();
I didn't, but as it turns out, this does not close the FileStream used by the XmlWriter. The docs for XmlWriter.Close say “closes this stream and the underlying stream”. Hmm...
Looking at the implementation, the reason for the behaviour becomes obvious:
XmlWriter:
public static XmlWriter Create(Stream output)
{
return XmlWriter.Create(output, null);
}
public static XmlWriter Create(Stream output, XmlWriterSettings settings)
{
if (output == null)
{
throw new ArgumentNullException("output");
}
if (settings == null)
{
settings = new XmlWriterSettings();
}
return XmlWriter.CreateWriterImpl(output, settings.Encoding, settings.CloseOutput, settings);
}
XmlWriterSettings:
public XmlWriterSettings()
{
this.Reset();
}
public void Reset()
{
…
this.closeOutput = false;
…
}
So taking that into account you must either use another overload of XmlWriter.Create, passing in an instance of
XmlWriterSettings whose CloseOutput property is set to “true” or close the stream you pass to Create yourself.
Either way, to me the way the above usability example works is wrong and at least a documentation bug. Beware :)