Search code examples
c#filesystemsfile-monitoring

Detecting opening file (using c#)


Hello everybody and sorry if i duplicate question(my english so bad). Is there any way to be notified when files are opened by a user? Something like the FileSystemWatcher class, except with an "Opened" event? I just want detect opening file without changed or renamed this file. for example, now i detect renaming file and want detecting opening too

private void hookEvents(String path, String password)
    {
        FileSystemWatcher fsw = new FileSystemWatcher();
        fsw.Path = Path.GetDirectoryName(path);
        fsw.Filter = Path.GetFileName(path);
        fsw.Renamed += new RenamedEventHandler(onRenamed);
        fsw.EnableRaisingEvents = true;
    }

P.S. i hear some about filters and drivers, but i hope that c# have simple way for my request.


Solution

  • System.IO.FileSystemWatcher is built for monitoring file changes. As "opening a file" does not change the file itself, it won't work for sure.

    there are possible ways to do this

    Option 1

    You can detect if a file is in use either by a WMI Query (if your OS is windows based) or by opening the file for write (Exception occurs when file is in use).

    Option 2

    You could try to get a handle on the file, and see the which process has the ownership. If so, the file is open by somebody else. check this post Using C#, how does one figure out what process locked a file?