Search code examples
c#xmlfilestreamxmldocumentxmltextwriter

XmlDocument.WriteTo truncates resultant file


Trying to serialize an XmlDocument to file. The XmlDocument is rather large; however, in the debugger I can see that the InnerXml property has all of the XML blob in it -- it's not truncated there.

Here's the code that writes my XmlDocument object to file:

// Write that string to a file.
var fileStream = new FileStream("AdditionalData.xml", FileMode.OpenOrCreate, FileAccess.Write);
xmlDocument.WriteTo(new XmlTextWriter(fileStream, Encoding.UTF8) {Formatting = Formatting.Indented});
fileStream.Close();

The file that's produced here only writes out to line like 5,760 -- it's actually truncated in the middle of a tag!

Anyone have any ideas why this would truncate here?

Update: I found the source of the issue. I was not closing the XML Text Writer before closing the file stream! D'oh!


Solution

  • The XmlTextWriter wasn't closed properly. Woops!