FileSystemWatcher does not report changes in a locked file

后端 未结 6 890
清酒与你
清酒与你 2021-01-01 18:26

I\'m monitoring a folder using a FileSystemWatcher like this:

watcher = new FileSystemWatcher(folder);
watcher.NotifyFilter = NotifyFilters.Size;
watcher.Cha         


        
6条回答
  •  没有蜡笔的小新
    2021-01-01 19:02

    I ran into this same FileSystemWatcher issue while writing a Windows Service. The service was written in .NET and used a FileSystemWatcher to monitor log files generated by a third party product. During testing I performed actions within this third party product that I knew forced log entries to be written but my service's breakpoints never fired until I opened my target log file in notepad or refreshed my view in Windows Explorer.

    My solution was to create a FileInfo instance (we'll call that fileInfoInstance) at the same time as I created my FileSystemWatcher. Any time I start or stop my FileSystemWatcher I also start or stop a System.Threading.Timer whose callback invokes fileInfoInstance.Refresh() every N milliseconds. It appears that fileInfoInstance.Refresh() flushes the buffers/write caching and allows FileSystemWatcher events to raise in the same manner that hitting F5 does within Explorer.

    Interestingly (and sadly) enough fileInfoInstance.Directory.Refresh() didn't accomplish the same result, so if you're watching multiple files, even if they're all in the same directory and being watched by the same watcher, you'll need a FileInfo instance for each file you're watching and your timer callback should refresh them all with each "tick"...

    Happy coding.

    Brian

提交回复
热议问题