2016-01-13 189 views
1

我在調用加載後保存我的XML文件時遇到問題。這個函數被調用兩次 - 當「toSave」被設置爲false時,第二次被設置爲true。第二次,保存會導致異常。我試着向XMLReader添加一個Dispose和Close調用,但似乎沒有任何幫助。這裏是代碼:C#XMLDocument保存 - 進程無法訪問該文件,因爲它正在被另一個進程使用

// Check if the file exists 
if (File.Exists(filePath)) 
{ 
    try 
    { 
     // Load the file 
     XmlReaderSettings readerSettings = new XmlReaderSettings(); 
     readerSettings.IgnoreComments = true; 
     XmlReader reader = XmlReader.Create(filePath, readerSettings); 

     XmlDocument file = new XmlDocument(); 
     file.Load(reader); 

     XmlNodeType type; 
     type = file.NodeType; 
     if (toSave) 
      ModifyXMLContents(file.FirstChild.NextSibling, null); 
     else 
      PopulateNode(file.FirstChild.NextSibling, null); 

     // Save if we need to 
     if (toSave) 
      file.Save(filePath); 

     reader.Dispose(); 
     reader.Close(); 
    } 
    catch (Exception ex) 
    { 
     // exception is: "The process cannot access the file d:\tmp\10.51.15.2\Manifest.xml" because it is being used by another process 
     Console.WriteLine(ex.Message); 
    } 
} 

任何幫助將不勝感激。

+4

請不要張貼圖片的代碼。複製並粘貼到問題中 - 並非所有用戶都可以訪問該圖像,或者他們可能在移動設備上,並且無法清楚地看到圖像。 – Tim

+0

我建議在關於如何有效地創建XML文檔 在看這篇文章[其他XML技術(http://www.albahari.com/nutshell/ch11.aspx) – MethodMan

+0

您嘗試保存該文件在關閉之前讀者。讀者最有可能鎖定文件。嘗試調用'Save'收盤前的讀者(以及考慮使用'using'塊爲好)。 – Tim

回答

3

XmlReader創建你仍然是開放的,當你試圖挽救它,因此它被鎖定的文件,防止保存。

一旦加載到XmlDocument中,您不再需要讀者,因此您可以在嘗試保存之前關閉/處理它,然後保存就可以工作。

例如:

XmlReaderSettings readerSettings = new XmlReaderSettings(); 
readerSettings.IgnoreComments = true;    

XmlDocument file = new XmlDocument(); 

using (XmlReader reader = XmlReader.Create(filePath, readerSettings))    
    file.Load(reader); 

/* do work with xml document */ 

if (save) 
    file.Save(filePath); 
0

對我來說這是由文件引起被寫出來到一個目錄中有許多(100K)的其他文件。一旦我清除了所有其他文件,問題就消失了。 NTFS似乎在一個文件夾中出現非常大量的文件而變得怪異。

相關問題