Additional options for FileSystemEventHandler

I'm trying to write a program that could control several folders to create files and run the same action, but with different settings for each folder. My problem is specifying an additional parameter for FileSystemEventHandler. I create a new FileWatcher for each directory to monitor and add a 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 can I get the variable 'mSettings' passed to FileSystemWatcherCreated ()?

+6
c # filesystemwatcher
source share
4 answers
 foreach (String config in configs) { ... FileWatcher.Created += (s,e) => DoSomething(e.FullPath, mSettings); ... } 
+3
source share
 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); } 
+5
source share

You cannot request more information than the FileWatcher handler FileWatcher . However, you can create small classes that have access to the configuration, and also have a delegate that you can attach to the FileWatcher Created event

 class Program { static void Main(string[] args) { FileSystemWatcher watcher = new FileSystemWatcher("yourpath"); var configurations = new IConfiguration[] { new IntConfiguration(20), new StringConfiguration("Something to print") }; foreach(var config in configurations) watcher.Created += config.HandleCreation; } private interface IConfiguration { void HandleCreation(object sender, FileSystemEventArgs e); } private class IntConfiguration : IConfiguration { public IntConfiguration(int aSetting) { ASetting = aSetting; } private int ASetting { get; set; } public void HandleCreation(object sender, FileSystemEventArgs e) { Console.WriteLine("Consume your settings: {0}", ASetting); } } public class StringConfiguration : IConfiguration { public string AnotherSetting { get; set;} public StringConfiguration(string anotherSetting) { AnotherSetting = anotherSetting; } public void HandleCreation(object sender, FileSystemEventArgs e) { Console.WriteLine("Consume your string setting: {0}", AnotherSetting); } } } 
0
source share

You need to understand what you are using. FileSystemEventHandler definition -

public delegate void FileSystemEventHandler(object sender, FileSystemEventArgs e);

You cannot pass the third argument. I’m afraid that you may have to write your own additional code to transmit β€œmSettings” data.

0
source share

All Articles