Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么覆盖XML文件会创建额外的结束标记?_C#_.net_Xml_Xmldocument - Fatal编程技术网

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

C# 为什么覆盖XML文件会创建额外的结束标记?,c#,.net,xml,xmldocument,C#,.net,Xml,Xmldocument,我正在用C#创建一个应用程序,它必须将一些用户设置写入XML文件。它们读起来非常好,但当我试图写回它们时,它们会创建一个程序无法读取的额外结束标记 XML文件: <?xml version="1.0" encoding="utf-8" ?> <options> <fullscreen>False</fullscreen> <resolutionX>1280</resolutionX> <resolut

我正在用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>
我的结局是:

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

真的
1280
720
真的
4.
0
0
/选项>

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

doc.Save(stream);
stream.SetLength(stream.Position);
stream.Close();
单据保存(流);
流设置长度(流位置);

stream.Close()是。但最好只是用一个新文件覆盖文件。更少的混乱,更少的事故发生的机会,同时没有流保持打开。非常感谢!工作得很有魅力!您必须使用
XmlDocument
?如果可能的话,我会使用LINQ到XML。。。
doc.Save(stream);
stream.SetLength(stream.Position);
stream.Close();