Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reliable way of monitoring file changes in a directory using the .NET framework

I'm looking for a reliable way of looking for changes in a directory.

I have tried using the FileSystemWatcher, but it's rather inaccurate when many small files are created, changed or deleted. It misses about 1 or 2 % of the files in my tests. That is quite a lot when you are adding or changing thousands of files rapidly.

I have tried polling for changes at different intervals 500 ms, 2000 ms etc. In this case I get too many hits. That might have something to do with the resolution of timestamps on the FileInfo object.

So my question is; is it possible, using the .NET Framework, to get the the changes to a directory reliably?

-- Christian

like image 597
Christian Sparre Avatar asked Jan 31 '11 20:01

Christian Sparre


People also ask

How do I monitor file changes?

To monitor file changes, you must enable security auditing for the files and folders you want to monitor for changes and use the Event Log monitor to monitor the Security event log channel. This procedure of monitoring file system changes replaces the deprecated file system change monitor input.

How do I monitor a file in C#?

The option to monitor files with specific extensions can be set using the Filter property of the FileSystemWatcher class. You can also fine-tune FileSystemWatcher to monitor any change in file Attributes, LastAccess, LastWrite, Security, and Size data. The FileSystemWatcher class raises the events described in Table 1.

How do I monitor files in a folder?

You can use the ellipsis (...) button to browse for the folder. Select this option to monitor the files and folders in sub-folders in the Folder that you specified.

How do I monitor the file and folder changes in Windows?

Navigate to Computer Configuration -> Windows Settings -> Security Settings ->Local Policies -> Audit Policy. Under Audit Policy, select 'Audit object access' and turn auditing on for both success and failure.


1 Answers

Have you tried increasing the InternalBufferSize? What size have you set it to?

From MSDN:


Note that a FileSystemWatcher may miss an event when the buffer size is exceeded. To avoid missing events, follow these guidelines: Increase the buffer size by setting the InternalBufferSize property. Avoid watching files with long file names, because a long file name contributes to filling up the buffer. Consider renaming these files using shorter names.


Keep your event handling code as short as possible.

like image 123
santiagoIT Avatar answered Sep 28 '22 14:09

santiagoIT