[英]how can i enable filesystemwatcher to fire each and every file created event without loosing any
[英]How can I determine which file filter was matched for a FileSystemWatcher event?
我正在使用FileSystemWatcher
,如下所示:
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;
OnCreated
事件处理程序定义如下:
private static void OnCreated(object sender, FileSystemEventArgs e)
{
string value = $"Created: {e.FullPath}";
Console.WriteLine(value);
}
现在,我想知道是否有一种方法可以准确地从“ Filters
”列表中指定的哪个过滤器中找到事件已引发?
例如,
OnCreated
事件处理程序观看C:\FileWatcherDemo
。"f1_\*.txt"
和"f2_\*.txt"
被添加到Filters
中。"f1_demo.txt"
添加到文件夹中。sender
object 和FileSystemEventArgs
作为参数传递给我的OnCreated
处理程序。 我怎么知道OnCreated
事件实际上是由"f1_*.txt"
过滤器匹配的?
您可能希望考虑使用 Microsoft 的 Reactive Framework (aka Rx) - NuGet System.Reactive
并using System.Reactive.Linq;
- 然后你可以这样做:
IObservable<(NotifyFilters NotifyFilter, FileSystemEventArgs FileSystemEventArgs)> query =
from nf in new []
{
NotifyFilters.Attributes,
NotifyFilters.CreationTime,
NotifyFilters.DirectoryName,
NotifyFilters.FileName,
NotifyFilters.LastAccess,
NotifyFilters.LastWrite,
NotifyFilters.Security,
NotifyFilters.Size,
}.ToObservable()
from u in Observable.Using(
() => new FileSystemWatcher(@"C:\path\to\folder"),
fsw => Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(h => fsw.Created += h, h => fsw.Created -= h))
select (nf, u.EventArgs);
IDisposable subscription =
query.Subscribe(x =>
{
Console.WriteLine($"Created: {x.FileSystemEventArgs.FullPath}");
Console.WriteLine($"Created: {x.NotifyFilter}");
});
它有效地为每个过滤器创建单独的FileSystemWatcher
实例,但生成单个合并的 stream 事件,保留使用的NotifyFilter
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.