如何使用 XDocument 保存到同一个文件?

How to save to the same file with XDocument?

我正在尝试编辑 xml 文件。
但是 document.Save() 方法必须使用另一个文件名。
有没有办法使用相同的文件?或其他方法。谢谢!

string path = "test.xml";
using (FileStream xmlFile = File.OpenRead(path))
{
    XDocument document = XDocument.Load(xmlFile);

    var setupEl = document.Root;

    var groupEl = setupEl.Elements().ElementAt(0);
    var valueEl = groupEl.Elements().ElementAt(1);

    valueEl.Value = "Test2";

    document.Save("test-result.xml");

    // document.Save("test.xml"); I want to use this line.
}

我收到错误:

The process cannot access the file '[...]\test.xml' because it is being used by another process.

问题是您试图在文件打开时写入文件。但是,一旦加载了 XML 文件,就无需打开它。只需更精细地确定代码范围即可解决问题:

string path = "test.xml";
XDocument document;
using (FileStream xmlFile = File.OpenRead(path))
{
    document = XDocument.Load(xmlFile);
}
// the rest of your code