c# - 为什么我的 XmlDocument.Save() 失败并返回 "Resource in use by another process"?

标签 c# xml xmldocument

所以我需要打开一个 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/

相关文章:

c# - 未输出 XmlDocument 前缀

c# - 以互操作方式传递对象 - JavaBean 到 C#

c# - 为什么 String.Equals 返回 false?

c# - 使用 Moq 模拟接口(interface)时,方法会发生什么变化?

c# - Array.Length 和 Array.Count() 之间的区别

android - 滚动时工具栏不隐藏

php - 我有一个 iframe,我需要 Google 对其内容进行索引。这可能吗?

php - 使用 PHP DOMDocument 解析脏 html 代码有困难

c# - XML 文档中的多语言示例

c# - 将 aspx 文件加载到 xmldocument 中