Using FileSystemWatcher with multiple files

后端 未结 4 1199
小蘑菇
小蘑菇 2020-12-16 03:27

I want to use FileSystemWatcher to monitor a directory and its subdirectories for files that are moved. And then I want to trigger some code when all the files have been mov

4条回答
  •  时光说笑
    2020-12-16 04:34

    Rx - throttle - makes this job easy. Here is a testable, reusable solution.

    public class Files
    {
         public static FileSystemWatcher WatchForChanges(string path, string filter, Action triggeredAction)
                {
                    var monitor = new FileSystemWatcher(path, filter);
    
                    //monitor.NotifyFilter = NotifyFilters.FileName;
                    monitor.Changed += (o, e) => triggeredAction.Invoke();
                    monitor.Created += (o, e) => triggeredAction.Invoke();
                    monitor.Renamed += (o, e) => triggeredAction.Invoke();
                    monitor.EnableRaisingEvents = true;
    
                    return monitor;
                }
    }
    

    Lets merge events into a single sequence

      public IObservable OnUpdate(string path, string pattern)
            {
                return Observable.Create(o =>
                {
                    var watcher = Files.WatchForChanges(path, pattern, () => o.OnNext(new Unit()));
    
                    return watcher;
                });
            }
    

    then finally, the usage

    OnUpdate(path, "*.*").Throttle(Timespan.FromSeconds(10)).Subscribe(this, _ => DoWork())
    

    u can obviously play with the throttle speed to suit your needs.

提交回复
热议问题