3

I am looking for a way to watch a directory (and its sub-directories) for locked files i.e. when an application opens a file and locks it, an event should trigger in my app.

So far I have been using FileSystemWatcher for other purposes like detecting rename, update, etc. But watching lock [using last access] requires a registry tweak as specified Here which is not an option so far.

Other solution that I have thought so far is continuously look for change in 'LastAccess' attribute using FileInfo object from another thread and verify if the file is locked.

Is there a better solution?

Community
  • 1
  • 1
Akshay Vats
  • 170
  • 9
  • I am not looking for a particular file. Here I have a directory and I need to watch for locking of file(s) in that directory. – Akshay Vats Jun 06 '14 at 13:09
  • If you wanted to do this efficiently (and reliably) you would probably need to look at implementing your own [minifilter driver](http://msdn.microsoft.com/en-gb/library/windows/hardware/ff540402(v=vs.85).aspx) and hooking into the appropriate API. – James Jun 06 '14 at 13:31

2 Answers2

1

Unfortunately, there is no way to see if a file is locked by a process.

But you can always try yourself to access the file and fire an event based on that:

public bool IsFileLocked(string filePath)
{
    try
    {
        using (File.Open(filePath, FileMode.Open)){}
    }
    catch (IOException e)
    {
        retturn true;
    }  

    return false;
}

This function will return true when your application could not access the file (thus it's in use by another program), false otherwise.

Complexity
  • 5,682
  • 6
  • 41
  • 84
0

You can try to check handle.exe by Sysinternals, someone had similar question: Check for locked files in Directory and find locking applicaiton

I guess you might call this from your app.

Community
  • 1
  • 1
przmk
  • 21
  • 5