开发者

Why is my XmlDocument.Save() failing with "Resource in use by another process"?

So I need to open an XML document, write to it and then save the file back to disk. Do I need to load the XmlDocument using a filestream to ensure that the stream is closed before saving?

 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!


I've run into this before. Instead of passing the path directly to Load, create an XmlReader that you can dispose of after the load:

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!
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜