2014-10-18 64 views
0

文件使用的例外所以我這樣做:獲取使用FileSystemWatcher的

public MainWindow() 
{ 
    InitializeComponent(); 

    FileSystemWatcher watcher = new FileSystemWatcher(); 
    watcher.Path = "F:\\Scoreboard Assistant\\output\\"; 
    watcher.Filter = "event.xml"; 
    watcher.NotifyFilter=NotifyFilters.LastWrite; 
    watcher.Changed += new FileSystemEventHandler(file_Changed); 
    watcher.EnableRaisingEvents = true; 
} 

private void file_Changed(object sender, FileSystemEventArgs e) 
{ 
    XmlDocument config = new XmlDocument(); 
    config.Load(e.FullPath.ToString()); 
    string text1 = config.SelectSingleNode("event/text1").InnerText; 
    string text2 = config.SelectSingleNode("event/text2").InnerText; 
} 

什麼我做的是看更改到一個特定的XML文件。然後,如果檢測到對文件的更改,它將讀取XML文件並從中提取變量。但是,當我運行代碼時,出現以下錯誤:

An unhandled exception of type 'System.IO.IOException' occurred in System.Xml.dll

Additional information: The process cannot access the file 'F:\Scoreboard Assistant\output\event.xml' because it is being used by another process.

如何解決此問題?

回答

1

FileSystemWatcher可以在寫入文件時引發多個寫入事件。事實上,它會在每個緩衝區刷新時產生一個事件。此錯誤意味着其他一些進程寫入該文件,但尚未完成

你是如何處理這個問題的?只需忽略此錯誤,並在您收到的下一個寫入事件中再次嘗試。您可能會看到文件被鎖定的幾個寫入事件,但在收到最後一個事件時,它應該已被其他進程解鎖。

+0

謝謝。我沒有意識到改變的事件會被解僱這麼多次。把我的代碼放入一個空的try-catch中修復它。 – 2014-10-18 22:00:32