Using C#, how does one figure out what process locked a file?

Viewed 57096

In Windows, how do I determine (using C#) what process locked a file?

Third-party tools are helpful, but not what I'm looking for.

9 Answers

Not very straightforward, but on Windows Vista and above you can use the Restart Manager APIs to see who is using a file. Internet Explorer caches settings includes details on using this to detect which process has iexplore.exe open.

Omitting a lot of detail:

// Start an RM session
RmStartSession(&sessionHandle, 0, sessionKey);

// Register the file you are checking
RmRegisterResources(sessionHandle, 1, filePathArray, 0, NULL, 0, NULL);

// Get all processes that have that file open.
RmGetList(sessionHAndle, &nProcInfoNeeded, &nProcInfo, processes, &rebootReason);
RmEndSession(sessionHandle);

Handle, from Windows Sysinternals. This is a free command-line utility provided by Microsoft.

You could run it, and parse the result.

Try Unlocker. If you try and delete the file that is locked by another process, it will list the process(es) that have the file locked. You can then unlock the file by shutting down those processes.

I believe that you need code running in kernel mode to completely answer the question (but I haven't looked at the restart manager API).

You can enumerate all processes and their modules - so if the file you're looking for is a module (DLL, EXE, OCX...), you're good to go. But if it's a text file for example, you have to look at the kernel handle table which you cannot see from user mode. Handle.exe has a kernel driver in order to do that.

You absolutely don't need to run in Kernel mode (!!!)
It's a Win32 FAQ since Windows 95 (!) (in C, Google groups, Win32) : read the handle table, from User mode of course, and get the PID from the File handle ...

Related