Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Additional parameters for FileSystemEventHandler

I'm trying to write a program that could monitor multiple folders for file creations and launch the same action but with different settings for each folder. My problem is in specifying an extra parameter for the FileSystemEventHandler. I create a new FileWatcher for each directory to monitor and add the handler for the Created-action:

foreach (String config in configs)
{
    ...
    FileWatcher.Created += new System.IO.FileSystemEventHandler(FileSystemWatcherCreated)
    ...
}

void FileSystemWatcherCreated(object sender, System.IO.FileSystemEventArgs e, MySettings mSettings)
{
    DoSomething(e.FullPath, mSettings);
}

How could I get the 'mSettings' variable passed to FileSystemWatcherCreated()?

like image 582
peku Avatar asked Apr 14 '10 09:04

peku


2 Answers


foreach (String config in configs) 
{ 
    ... 
    MySettings mSettings = new MySettings(...); // create a new instance, don't modify an existing one
    var handler = new System.IO.FileSystemEventHandler( (s,e) => FileSystemWatcherCreated(s,e,msettings) );
    FileWatcher.Created += handler;
    // store handler somewhere, so you can later unsubscribe
    ... 
} 

void FileSystemWatcherCreated(object sender, System.IO.FileSystemEventArgs e, MySettings mSettings) 
{ 
    DoSomething(e.FullPath, mSettings); 
} 
like image 174
Henrik Avatar answered Sep 25 '22 02:09

Henrik


foreach (String config in configs)
{
    ...
    FileWatcher.Created += (s,e) => DoSomething(e.FullPath, mSettings);
    ...
}
like image 45
leppie Avatar answered Sep 23 '22 02:09

leppie