Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch folder for files being Read

I am trying to watch files in a directory to determine when files are opened/accessed. I thought FileSystemWatcher would do the trick using the event Changed.

Problem is that some applications do not create a lock on the file they open/access or change either the date modified or date accessed (even after fsutil behavior set disablelastaccess 0). Notepad for example. Apparently is makes a copy of the file in memory and plays with it there until you save it. Nor does it update the Date Accessed.

How can I monitor a directory of files and be notified when a file is simply opened/accessed by any program (e.g. Notepad)? Files may be opened from another computer, not necessarily on the computer running the "watcher".

I found lots of similar questions but did not see one focusing on file "access".

like image 803
Kez Avatar asked Feb 05 '11 17:02

Kez


1 Answers

This is quite normal. Updating an existing file is quite dangerous since it can cause irretrievable data loss. A disk error (like disk full) while writing is very bad news. The common algorithm used:

  • rename the original file
  • write a new file using the original name
  • no error: delete the renamed file
  • error: delete the new file, rename original file back

Clearly this doesn't cause a Changed event to be raised, no file was changed.


Sorry, I didn't read the question well enough. There is no notification whatsoever for an app just opening a file for reading. FSW can only detect changes to the file system. There is no ready alternative either, this requires a custom file system filter driver that snoops on driver requests. Like the kind that SysInternals' ProcMon utility uses. I'm not aware of such a driver ready for use in a C# program, you can't write them in C# either. This just isn't a common requirement.

like image 86
Hans Passant Avatar answered Oct 06 '22 01:10

Hans Passant