为什么覆盖XML文件会创建额外的结束标记?

时间:2013-05-05 15:18:59

标签: c# .net xml xmldocument

我在C#中创建一个必须将一些用户设置写入XML文件的应用程序。它们读得非常好,但是当我尝试将它们写回来时,它们会创建一个程序无法读取的额外结束标记。

XML文件:

<?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>

写的代码:

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();

我最终得到的结果:

<?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>

1 个答案:

答案 0 :(得分:3)

由于您正在写入相同的流,如果修改后的XML比原始XML短,则差异将保持不变。保存后可以使用FileStream.SetLength来修复:

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