Try this code:
static void Main(string[] args)
{
string fileName = @"D:\test\xml\2.xml";
XmlDocument document = LoadDocument(fileName);
XmlNodeList nodes = document.SelectNodes("//Items//Item");
XmlNode node = nodes[0].SelectSingleNode("//Quantity");
node.InnerText = "3";
SaveDocument(document, fileName);
Console.ReadLine();
}
public static XmlDocument LoadDocument(String path)
{
XmlDocument document = new XmlDocument();
using (StreamReader stream = new StreamReader(path))
{
document.Load(stream);
}
return (document);
}
public static XmlDocument SaveDocument(XmlDocument document, String path)
{
using (StreamWriter stream = new StreamWriter(path))
{
document.Save(stream);
}
return (document);
}
It cannot prevent two programs from accessing the same program. After all, if App1's operation on this file has ended, then there is no reason to prevent App2 from operating this file.
But it can report an exception when App2 tries to modify the file before App1 finishes modifying the file.
For example, you can add a breakpoint on line 26 of the above code, run the project, and then run another project that accesses this file, you will see:
You can catch this exception and deal with it to achieve your needs.
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.