Why does overwriting an XML file create an extra end tag?

倖福魔咒の 提交于 2019-12-24 01:04:40

问题


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>

回答1:


Since you’re writing to the same stream, if the modified XML is shorter than the original, the difference will remain. You can use FileStream.SetLength after saving to fix that:

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


来源:https://stackoverflow.com/questions/16385973/why-does-overwriting-an-xml-file-create-an-extra-end-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!