所以我需要打开一个 XML 文档,写入它,然后将文件保存回磁盘。我是否需要使用文件流加载 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!
最佳答案
我以前遇到过这个。不要将路径直接传递给 Load,而是创建一个可以在加载后处理的 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!
关于c# - 为什么我的 XmlDocument.Save() 失败并返回 "Resource in use by another process"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6603822/