2012-02-17 163 views
9

我有一個創建一個基本的XML文件,並保存一個簡單的C#功能:XmlDocument的保存保持文件打開

private void CreateXMlFile(string Filename, string Name, string Company) 
     { 
      XmlDocument doc = new XmlDocument(); 
      XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); 
      doc.AppendChild(docNode); 

      XmlNode licenseNode = doc.CreateElement("license"); 
      doc.AppendChild(licenseNode); 

      XmlNode node = doc.CreateElement("Name"); 
      node.AppendChild(doc.CreateTextNode(Name)); 
      licenseNode.AppendChild(node); 

      node = doc.CreateElement("Company"); 
      node.AppendChild(doc.CreateTextNode(Company)); 
      licenseNode.AppendChild(node); 


      doc.Save(Filename); 
     } 

當我嘗試編輯或刪除的文件我總是得到以下錯誤:

The process cannot access the file because it is being used by another process.

XmlDocument沒有任何內置的配置或關閉例程,並想知道如何在稍後編輯或刪除它之前強制關閉文件。

我曾嘗試使用的StreamWriter來保存文件:

StreamWriter outStream = System.IO.File.CreateText(outfile); 
      outStream.Write(data); 
      outStream.Close(); 

但這didnt使具有相同錯誤的差異。

您的建議很受歡迎。

謝謝

+0

您是否試圖用流寫入的實例編寫而不是傳遞文件名來保存? – Steve 2012-02-17 11:01:12

+0

我有同樣的問題,但我的代碼首先加載XML,如果它存在。在釋放文件鎖定之前,需要關閉「XmlReader」對象。 – 2015-04-21 06:59:01

回答

1

你的代碼沒問題。我在我的機器上進行了測試,Save()後沒有任何鎖定。

嘗試使用Unlocker(http://www.softpedia.com/get/System/System-Miscellaneous/Unlocker.shtml)檢查您是否真的是持有鎖的人。

你使用哪個.NET框架?這也是一個不可重現的報告(http://bytes.com/topic/net/answers/467028-xmldocument-save-does-not-close-file-properly)。

+0

它被視覺工作室vshost.exe鎖定。我剛剛編譯爲.net 3.5和相同的問題。 – Belliez 2012-02-17 11:55:11

+0

您可以用按鈕點擊調用該方法創建一個空白項目,並在點擊後檢查該文件是否被鎖定? – BlueM 2012-02-17 12:27:49

4

發送流到XmlDocument的保存方法,而不是文件名。

private static void Main(string[] args) 
    { 
     CreateXMlFile("c:\\test.xml", "testName", "testCompany"); 
    } 

    private static void CreateXMlFile(string Filename, string Name, string Company) 
    { 
     XmlDocument doc = new XmlDocument(); 
     XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); 
     doc.AppendChild(docNode); 

     XmlNode licenseNode = doc.CreateElement("license"); 
     doc.AppendChild(licenseNode); 

     XmlNode node = doc.CreateElement("Name"); 
     node.AppendChild(doc.CreateTextNode(Name)); 
     licenseNode.AppendChild(node); 

     node = doc.CreateElement("Company"); 
     node.AppendChild(doc.CreateTextNode(Company)); 
     licenseNode.AppendChild(node); 
     StreamWriter outStream = System.IO.File.CreateText(Filename); 

     doc.Save(outStream); 
     outStream.Close(); 
    } 

我試着執行上面的代碼,它在我的最後工作正常。

+0

我試過這個,當我去刪除文件時,我得到同樣的錯誤。 – Belliez 2012-02-17 11:43:25

+0

你可以嘗試更改文件位置嗎? – AshokD 2012-02-17 11:52:01

+0

也嘗試了新的位置。我還禁用Livedrive(在線備份)以防萬一這是干擾。 – Belliez 2012-02-17 11:58:54