9

In C++ (specifically on Visual C++), sometimes you cannot open a file because another executable has it opened and is not sharing it for reads. If I try to open such a file, how can I programatically find out who's locking the file?

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
Warpin
  • 6,971
  • 12
  • 51
  • 77

2 Answers2

13

In Windows 2000 and higher, you cannot do this without using a kernel-mode driver. Process Explorer and other similar tools load a driver automatically to accomplish this. This is because the file handles are in kernel space and not accessible by user-mode applications (EXE files).

If you are really interested in doing this, take a look at this project.

Dumb Guy
  • 3,336
  • 21
  • 23
  • 1
    You can see that Process Explorer is loading a driver by looking at the DLLs of the `System` process; you will see a driver similar to `PROCEXP113.SYS` loaded – Dumb Guy Jan 02 '10 at 03:53
5

The MSDN approved way is IFileIsInUse::GetAppName(). Requires Vista, though.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • 2
    This seems to require cooperation from the program that opened a file, which is not the same as what is being asked. – user541686 Aug 26 '13 at 07:18
  • It's the most information-rich way, which is why you should try it first. – MSalters Aug 26 '13 at 09:16
  • 3
    Sure, there's no harm in trying it, but the chances that it works are very low so the OP will most likely need an alternative regardless. – user541686 Aug 26 '13 at 09:18