Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么我的XmlDocument.Save()会失败,并带有;另一进程正在使用的资源;?_C#_Xml_Xmldocument - Fatal编程技术网

C# 为什么我的XmlDocument.Save()会失败,并带有;另一进程正在使用的资源;?

C# 为什么我的XmlDocument.Save()会失败,并带有;另一进程正在使用的资源;?,c#,xml,xmldocument,C#,Xml,Xmldocument,所以我需要打开一个XML文档,写入它,然后将文件保存回磁盘。我是否需要使用filestream加载XmlDocument,以确保在保存之前关闭该流 string xmlPath = Server.MapPath("../statedata.xml"); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(xmlPath); XmlNode node =

所以我需要打开一个XML文档,写入它,然后将文件保存回磁盘。我是否需要使用filestream加载XmlDocument,以确保在保存之前关闭该流

 string xmlPath = Server.MapPath("../statedata.xml");
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(xmlPath);
            XmlNode node = xmlDocument.SelectSingleNode("//root/state");
            node.InnerText = string.Format("org.myorg.application.init = {0};",stateJson);
            xmlDocument.Save(xmlPath); //blows up!

我以前碰到过这个。不要直接将路径传递给加载,而是创建一个XmlReader,您可以在加载后处理它:

string xmlPath = Server.MapPath("../statedata.xml");
XmlDocument xmlDocument = new XmlDocument();  
using(XmlReader reader = XmlReader.Create(xmlPath)) 
   xmlDocument.Load(reader);         

XmlNode node = xmlDocument.SelectSingleNode("//root/state");
node.InnerText = string.Format("org.myorg.application.init = {0};",stateJson);    
xmlDocument.Save(xmlPath); //blows up!

看起来,
XmlDocument
保持文件打开(并因此锁定)System.Xml有点糟糕,但也没那么糟糕。它在finally块中关闭读卡器。显然,该文件正在其他地方使用。可能在另一个web请求线程中。