xdocument save adding extra characters
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开发者_如何学JAVA>
<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 reading foo.xml
, and one for overwriting it. That seems very problematic.
I'd recommend:
- Disposing of the read
FileStream
as soon as yourXmlDocument
is loaded:
using (FileStream fs = new FileStream(@"C:\foo.xml", FileMode.Open, FileAccess.Read))
{
config.Load(fs);
}
- Use
FileMode.Truncate
in your writeFileStream
so that the file is truncated to 0 bytes before you start writing to it.
My guess is that something's actually overwriting (but not truncating) the file with fewer tags - and what you're seeing is the remains of a larger XML file.
I've never seen LINQ to XML do anything like this itself.
Can you run the same tests which always fail, but in a mode where each iteration writes to a new file instead of overwriting the old one?
Is there any reason you're loading directly from FileStreams
(which are never being closed, as another answer points out) instead of just using XDocument.Load(filename)
, XDocument.Save(filename)
?
I've seen this before... just can't think how to resolve it. I think it's got something to do with the way you are saving. You need to make sure you overwrite everything. I can't remember if it's the filemode or options... or another setting
精彩评论