2016-02-29 14 views
0

我的XmlDocument類有一個奇怪的問題。XmlDocument問題使用拋出異常後直接打開XML文件

我用它寫了一些XML文件,效果很好。 我有Save()方法:

public void Save() 
{ 
    var xwSettings = new XmlWriterSettings 
    { 
     Encoding = new UTF8Encoding(false), 
     Indent = true, 
     IndentChars = "\t" 
    }; 
    using (XmlWriter xw = XmlWriter.Create(new FileStream(this.FilePath, FileMode.Create), xwSettings)) 
    { 
     XmlDocument.WriteTo(xw); 
    } 
} 

像其他人看到,我使用的是「使用」,這應該給XML免費:) 但是,如果我嘗試調用保存後直接讀取這個文件()我得到以下例外:

進程無法訪問文件「___。xml」,因爲它已被另一進程使用。

有人能解釋一下,給我一個解決方案嗎?

親切的問候

回答

2

你沒有處理你的文件流。嘗試像這樣改變你的代碼。

 using (var xmlStream = new FileStream(this.FilePath, FileMode.Create)) 
     { 
      using (XmlWriter xw = XmlWriter.Create(xmlStream, xwSettings)) 
      { 
       var xDoc = new XmlDocument(); 
       xDoc.WriteTo(xw); 
      } 
     } 
+0

我以爲處置XmlWriter會自動處理FileStream。但我試過了,你說的對,thx! – SharpNoiZy

相關問題