Adrian Hara

Working through the .NET maze

  Home  |   Contact  |   Syndication    |   Login
  42 Posts | 0 Stories | 83 Comments | 10 Trackbacks

News

Archives

Post Categories

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

Feedback

# re: XmlWriter's Close bug 2/7/2007 3:33 PM Alexis Seigneurin
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... :)

# re: XmlWriter's Close bug 2/7/2007 3:35 PM Adrian Hara
Glad to help. I got the "source code" using Lutz Roeder's Reflector tool.

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: