所以我需要打开一个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!
答案 0 :(得分:4)
我之前遇到过这种情况。不要将路径直接传递给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!