2011-07-06 64 views
4

所以我需要打開一個XML文檔,寫入它,然後將文件保存回磁盤。我是否需要使用文件流加載XmlDocument以確保在保存之前關閉了流?爲什麼我的XmlDocument.Save()失敗「正在使用另一個進程的資源」?

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! 
+1

它看起來像'XmlDocument'保持打開該文件(並因此鎖定) – Earlz

+0

的System.Xml是有點兒蘇茨基,但它不*那*不好。它在finally塊中關閉了讀者。顯然該文件正在其他地方使用。可能在另一個Web請求線程中。 –

回答

4

我以前碰到過這個。而不是直接傳遞路徑的負載,創建一個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! 
相關問題