I would like to close the handles of all processes that access a certain file. To retrieve the processes, I use the solution of Eric J. in this thread. Now, unfortunately, it does not work to close the Process.Handle
with the Winapi function CloseHandle()
. The Process
class returns the correct pid, but not the correct handle.
This can also be seen when using Handle from Mark Russinovich. This returns a different handle, which you can actually close with the given function.
So, can I get the file locking handle from the Process
class? And if not, which Winapi should I use for it?
(Working) Handle by Mark Russinovich:
C:\dev\Handles\Handle>handle.exe C:\dev\Handles\test.accdb
MSACCESS.EXE pid: 5952 type: File EA4: C:\dev\Handles\test.accdb
Process Handle:
List<Process> LockingProcesses = FileUtil.WhoIsLocking(@"C:\dev\Handles\test.accdb");
foreach (Process process in LockingProcesses)
{
CloseHandle(process.Handle);
}
Solution (credit to Remy Lebeau):
Handle.exe
is reporting the actual file handle within the target process. Process.Handle
returns the process handle of the EXE file that created the process which FileUtil.WhoIsLocking()
says has the target file open. Two completely different things, which is why they are different values.
See How can I close a handle in another process? for a detailed explanation of how to find and close handles in other processes, similar to how SysInternals Process Explorer does.