views:

205

answers:

3

I would like to know if a file is open by any process (including the caller) There are a number of suggestions already posted, which tend to revolve around trying to open the file exclusively and catching the exception.

This has not proven to be a fool-proof method in my instance. I beleive in my specific situation I can get by with scanning the names all open handles of type File of all running processes.

+1  A: 

a poor man's way would be to shell to handle.exe from sysinternals. i don't know if it can be distributed. it must be run as admin (i'm pretty sure you need admin rights to do what you want anyway). anyway, if you can just shell to it and redirect the output to a file or capture its stdout, then you just have to parse its output to get what you want. i did a search in the internet wayback and it doesn't appear that mark r. ever released the source to his utility.

this obviously isn't a good solution if you have an app you distribute, but if its just in-house perhaps this would be good enough.

best regards, don

Don Dickinson
A: 

As i remember code handle.exe have open sources so you can use this great utility as reference.

Pirks
+1  A: 

I don't think that you can solve this problem simply with .NET and P/Invoke. You will need to access low-level functionality. See the solution posted by AdaraCD in this thread in another forum which is using the driver development kit (DDK):

Enum HANDLEs for a process

0xA3