2011-10-18 83 views
0

我想使用多個FileSystemWatchers觀看不同的文本文件。使用多個FileSystemWatchers

我成功地創造了觀察者和被調用的文件更改事件,我可以添加在文本文件中的變化爲字符串,並在窗體上顯示此。

我想知道的是我怎麼能分出哪個觀察者導致了事件?

例如, watcher1,watcher2或watcher3?

我知道我可以找出已更改的文件的路徑和文件名,但是這並不能真正幫助我。

+0

還沒有答案。我想我設法解決了我自己的問題。我創建了一個包含用於不同觀察者的文件路徑的數組。這使我能夠將觀察者與陣列聯繫起來,並找出哪些事件觸發了哪些事件。 – alexwiese

回答

1

我知道你已經找到自己的方式做到這一點,但我建議你看那個被解僱的事件中發送參數。這在很多事件中都很常見。這裏是一個小例子:

private static FileSystemWatcher watcherTxt; 
private static FileSystemWatcher watcherXml; 

static void Main(string[] args) 
{ 
    String dir = @"C:\temp\"; 

    watcherTxt = new FileSystemWatcher(); 
    watcherTxt.Path = dir; 
    watcherTxt.Filter = "*.txt"; 
    watcherTxt.EnableRaisingEvents = true; 
    watcherTxt.Created += new FileSystemEventHandler(onCreatedFile); 

    watcherXml = new FileSystemWatcher(); 
    watcherXml.Path = dir; 
    watcherXml.Filter = "*.xml"; 
    watcherXml.EnableRaisingEvents = true; 
    watcherXml.Created += new FileSystemEventHandler(onCreatedFile); 

    Console.ReadLine(); 
} 

private static void onCreatedFile(object sender, FileSystemEventArgs e) 
{ 
    if (watcherTxt == sender) 
    { 
     Console.WriteLine("Text Watcher Detected: " + e.FullPath); 
    } 

    if (watcherXml == sender) 
    { 
     Console.WriteLine("XML Watcher Detected: " + e.FullPath); 
    } 
}