I've seen several of answers about using Handle or Process Monitor, but I would like to be able to find out in my own code (C#) which process is locking a file.
I have a nasty feeling that I'm going to have to spelunk around in the win32 API, but if anyone has already done this and can put me on the right track, I'd really appreciate the help.
Long ago it was impossible to reliably get the list of processes locking a file because Windows simply did not track that information. To support the Restart Manager API, that information is now tracked.
I put together code that takes the path of a file and returns a
List<Process>
of all processes that are locking that file.Using from Limited Permission (e.g. IIS)
This call accesses the registry. If the process does not have permission to do so, you will get ERROR_WRITE_FAULT, meaning
An operation was unable to read or write to the registry
. You could selectively grant permission to your restricted account to the necessary part of the registry. It is more secure though to have your limited access process set a flag (e.g. in the database or the file system, or by using an interprocess communication mechanism such as queue or named pipe) and have a second process call the Restart Manager API.Granting other-than-minimal permissions to the IIS user is a security risk.
I had issues with stefan's solution. Below is a modified version which seems to work well.
UPDATE
If you just want to know which process(es) are locking a particular DLL, you can execute and parse the output of
tasklist /m YourDllName.dll
. Works on Windows XP and later. SeeWhat does this do? tasklist /m "mscor*"
It is very complex to invoke Win32 from C#.
You should use the tool Handle.exe from http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx
After that your C# code have to be the following:
simpler with linq:
This works for dlls locked by other processes. This routine will not find out for example that a textfile is locked by a wordprocess.
C#:
VB.Net:
One of the good things about
handle.exe
is that you can run it as a subprocess and parse the output.We do this in our deployment script - works like a charm.