实测,在文件进行读写的时候,使用xmlDocument.Save("1.txt");
进行文件保存时,会出现以下异常。
System.IO.IOException:“The process cannot access the file 'C:\Users\Shine\Desktop\ConsoleApp2\ConsoleApp2\bin\Debug\netcoreapp2.1\1.txt'
because it is being used by another process.”
此时可以使用ReaderWriterLockSlim
对文件进行保护,把xmlDocument.Save
当作一个FileStream file = new FileStream("1.txt", FileMode.Open, FileAccess.ReadWrite);
来看待。
如:
static void SaveXml()
{
Console.WriteLine(DateTime.Now.ToString() + " " + "SaveXml");
lockSlim.EnterWriteLock();
try
{
Console.WriteLine(DateTime.Now.ToString() + " " + "xmlDocument begin save");
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(@"<note>
<to> George </to>
<from> John </from>
<heading> Reminder </heading>
<body> Don't forget the meeting!</body>
</note>");
xmlDocument.Save("1.txt");
Console.WriteLine(DateTime.Now.ToString() + " " + "xmlDocument Save ok");
}
finally
{
lockSlim.ExitWriteLock();
}
}