The Inquisitive Coder – Davy Brion's Blog

Trying to walk that thin line between intelligence and ignorance

XDocument’s WriteTo method gotcha

Posted by Davy Brion on April 25th, 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…

One Response to “XDocument’s WriteTo method gotcha”

  1. Justice Says:

    I have the same issue; and its friday afternoon!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>