2

I am creating an application in C# that has to write some user settings to an XML file. They are read perfectly fine, but when I try to write them back they create an extra end tag that the program cannot read.

XML file:

<?xml version="1.0" encoding="utf-8" ?>
<options>
   <fullscreen>False</fullscreen>
   <resolutionX>1280</resolutionX>
   <resolutionY>720</resolutionY>
   <vsync>True</vsync>
   <AA>2</AA>
   <musicvolume>0</musicvolume>
   <soundvolume>0</soundvolume>
</options>

Code that writes:

FileStream stream =
    new FileStream("configs/options.xml", FileMode.Open, FileAccess.ReadWrite);

XmlDocument doc = new XmlDocument();

doc.Load(stream);

stream.Seek(0, SeekOrigin.Begin);

doc.SelectSingleNode("/options/fullscreen").InnerText = fullscreen.ToString();
doc.SelectSingleNode("/options/vsync").InnerText = vsync.ToString();
doc.SelectSingleNode("/options/resolutionX").InnerText = resolutionX.ToString();
doc.SelectSingleNode("/options/resolutionY").InnerText = resolutionY.ToString();
doc.SelectSingleNode("/options/AA").InnerText = aa.ToString();
doc.SelectSingleNode("/options/musicvolume").InnerText = musicvolume.ToString();
doc.SelectSingleNode("/options/soundvolume").InnerText = soundvolume.ToString();

doc.Save(stream);
stream.Close();

What I end up with:

<?xml version="1.0" encoding="utf-8" ?>
<options>
   <fullscreen>True</fullscreen>
   <resolutionX>1280</resolutionX>
   <resolutionY>720</resolutionY>
   <vsync>True</vsync>
   <AA>4</AA>
   <musicvolume>0</musicvolume>
   <soundvolume>0</soundvolume>
</options>/options>
4

1 回答 1

3

由于您正在写入同一个流,如果修改后的 XML 比原始的短,那么差异仍然存在。您可以FileStream.SetLength在保存后使用来解决此问题:

doc.Save(stream);
stream.SetLength(stream.Position);
stream.Close();
于 2013-05-05T15:21:24.207 回答