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?

2
  • 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. Commented Jun 6, 2014 at 13:09
  • If you wanted to do this efficiently (and reliably) you would probably need to look at implementing your own minifilter driver and hooking into the appropriate API. Commented Jun 6, 2014 at 13:31

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

So your suggestion is to continuously attempt to open every file in the directory until you get an IOException? Terrible waste of resources.
Yes that's my last option.
@James I fear the same
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.