FileSystemwatcher for a list of files

后端 未结 1 702
醉梦人生
醉梦人生 2021-01-22 01:50

I have been following the guidance here FileSystemWatcher Changed event is raised twice.

However I have a list of files that I\'m watching so if I delete 20 files togeth

相关标签:
1条回答
  • 2021-01-22 02:18

    The key point here is what does "together" mean to you. after all the system does an independent delete operation for each, which would technically mean they are not all deleted at the exact same time, but if you just wanna be close, let's say if they are all deleted within 5 seconds of each other then we only want OnChange to fire once, you can do the following. Note that this doesn't handle the rename change notification. You weren't listening for it, so I assumed you don't need to.

    you may wanna change the 5 seconds window to a small window depending on your use.

        class SlowFileSystemWatcher : FileSystemWatcher
        {
            public delegate void SlowFileSystemWatcherEventHandler(object sender, FileSystemEventArgs args);
    
            public event SlowFileSystemWatcherEventHandler SlowChanged;
            public DateTime LastFired { get; private set; }
    
            public SlowFileSystemWatcher(string path)
                : base(path)
            {
                Changed += HandleChange;
                Created += HandleChange;
                Deleted += HandleChange;
                LastFired = DateTime.MinValue;
            }
    
            private void SlowGeneralChange(object sender, FileSystemEventArgs args)
            {
                if (LastFired.Add(TimeSpan.FromSeconds(5)) < DateTime.UtcNow)
                {
                    SlowChanged.Invoke(sender, args);
                    LastFired = DateTime.UtcNow;
                }
            }
    
            private void HandleChange(object sender, FileSystemEventArgs args)
            {
                SlowGeneralChange(sender, args);
            }
    
            protected override void Dispose(bool disposing)
            {
                SlowChanged = null;
                base.Dispose(disposing);
            }
        }
    
    0 讨论(0)
提交回复
热议问题