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!