XDocument’s WriteTo method gotcha
Posted by Davy Brion on 25th April 2008
Suppose you have an xml document in memory using an XDocument instance. Then you need to write the contents of the xml document to an XmlWriter… no worries, the XDocument class provides the WriteTo method which takes an XmlWriter as a parameter. The contents of the xml document are then nicely written to the XmlWriter.
Unless… you’re using an XmlWriter which was created with an XmlWriterSettings instance with OutputMethod set to XmlOutputMethod.Text and your xml document is larger than 6144 bytes! The writer will only write the first 6144 bytes and after that, it just stops. No exception, no nothing. The method returns as if everything was OK. But the underlying stream your XmlWriter wrote to contains faulty data. A very nice way to spend a friday afternoon
In case you’re wondering why: The XmlWriter’s static Create method creates an instance of XmlUtf8RawTextWriter when OutputMethod is set to XmlOutputMethod.Text. This specific Writer has an internal buffer which is initialized in its constructor to be 6144 bytes long. Apparantly, it doesn’t think it’s worth throwing an exception if you try to write too much data…
Posted in .NET bugs | No Comments »