Akshay Vats
Akshay Vats

Reputation: 170

C# - Detect locked files in a directory

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?

Upvotes: 3

Views: 1846

Answers (2)

przmk
przmk

Reputation: 21

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.

Upvotes: 0

Complexity
Complexity

Reputation: 5830

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.

Upvotes: 1

Related Questions