Home > Net >  How to save to the same file with XDocument?
How to save to the same file with XDocument?

Time:05-20

I'm trying to edit xml file.
but document.Save() method has to use another file name.
Is there any way to use same file? or other method. Thank you!

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.
}

I receive the error:

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

CodePudding user response:

The problem is that you are trying to write to the file while you still have it open. However, you have no need to have it open once you've loaded the XML file. Simply scoping your code more granularly will solve the issue:

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