I’m using XDocument to load and save a config file. Most of the time it works correctly, but there are cases (seemingly random) where it appends extra information after the last tag. Here’s a gist of what’s happening.
Config file pre-run:
<?xml version="1.0" encoding="us-ascii"?>
<local>
</local>
code:
XDocument config = new XDocument();
config = XDocument.Load(new FileStream(@"c:\foo.xml", FileMode.Open, FileAccess.Read));
XElement fileEle = config.Root.Element("files");
XElement statsEle = new XElement("stats");
statsEle.Add(new XElement("one", "two"));
statsEle.Add(new XElement("three", "four"));
.
.
.
fileEle.Add(statsEle);
config.Save(new FileStream(@"c:\foo.xml", FileMode.Create, FileAccess.Write), SaveOptions.None);
config file post-run:
<?xml version="1.0" encoding="us-ascii"?>
<local>
<files>
<one>two</one>
<three>four</three>
</files>
</local>s>
</local>
Any suggestions? No idea why the extra characters are being added. Sometimes it’s the extra tag, sometimes it’s different characters and sometimes it works correctly. I’ve tried loading/saving using different methods (XMLReader, etc.), adding XML tags different ways.. after X runs they all produce the same error. Thanks for the help!
You have two
FileStream‘s open for the same file concurrently… one for readingfoo.xml, and one for overwriting it. That seems very problematic.I’d recommend:
FileStreamas soon as yourXmlDocumentis loaded:FileMode.Truncatein your writeFileStreamso that the file is truncated to 0 bytes before you start writing to it.