2014-10-18 28 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