I am using a FileSystemWatcher as follows:
using watcher = new FileSystemWatcher(@"C:\path\to\folder");
watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;
watcher.Created += OnCreated;
watcher.Error += OnError;
foreach(string filter in filters)
{
watcher.Filters.Add(filter);
}
watcher.IncludeSubdirectories = false;
watcher.EnableRaisingEvents = true;
The OnCreated event handler is defined as follows:
private static void OnCreated(object sender, FileSystemEventArgs e)
{
string value = $"Created: {e.FullPath}";
Console.WriteLine(value);
}
Now, I want to know if is there a way I can find from exactly which filter specified in the Filters list has the event been raised?
For example,
- I am watching
C:\FileWatcherDemowith theOnCreatedevent handler. "f1_\*.txt"and"f2_\*.txt"are added toFilters.- I add
"f1_demo.txt"to the folder. - I have the
senderobject and theFileSystemEventArgspassed as argument to myOnCreatedhandler.
How can I know that the OnCreated event was actually matched by the "f1_*.txt" filter?
You may wish to consider using Microsoft's Reactive Framework (aka Rx) - NuGet
System.Reactiveand addusing System.Reactive.Linq;- then you can do this:It effectively creates separate
FileSystemWatcherinstances for each filter yet produces a single merged stream of events preserving theNotifyFilterused.