Geeks With Blogs
Adrian Hara Working through the .NET maze

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 :)

Posted on Tuesday, May 16, 2006 2:20 PM | Back to top


Comments on this post: XmlWriter's Close bug

# re: XmlWriter's Close bug
Requesting Gravatar...
There is indeed a bug here, at least in the documentation. Thanks for the explanation. It was definitely helpful.

But I am wondering where you took the source code from... :)
Left by Alexis Seigneurin on Feb 07, 2007 3:33 PM

# re: XmlWriter's Close bug
Requesting Gravatar...
Glad to help. I got the "source code" using Lutz Roeder's Reflector tool.
Left by Adrian Hara on Feb 07, 2007 3:35 PM

Your comment:
 (will show your gravatar)


Copyright © Adrian Hara | Powered by: GeeksWithBlogs.net