Search code examples
c#xmlxmldocument

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!

Solution

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