当前位置:   article > 正文

C# XmlDocument.Save文件操作System.IO.IOException:The process cannot access the file because it is being_system.io.ioexception: the process cannot access t

system.io.ioexception: the process cannot access the file

实测,在文件进行读写的时候,使用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.”
  • 1
  • 2

此时可以使用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();
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/215982
推荐阅读
相关标签
  

闽ICP备14008679号