I do not think you can tell why a process opened a file, but can tell the files the process currently holds open...
First of all you have to dig into old WIN32 API
NtQuerySystemInformation[
^]
This function is not much documented and the help page will not contain the
SystemHandleInformation enumerated value (16) for the first parameter, but still will have to use it...
You will have to call it twice, once the last parameter as return value of the needed buffers size, and a second time with NULL at the last parameter to actually retrieve the values...
The result of this function is a list of all handles (of all types) for all processes...You have to enumerate them and check the type and the process owns the handle...
Using
NtQueryObject[
^] in a loop (using ObjectNameInformation as second parameter), will provide you with the device based name of the file the handle holds...
To find the user friendly name you have to use
QueryDosDevice[
^] function - it will map device to letter...
Two things:
1. You have to duplicate the handle into your process before using it. Do it using
OpenProcess[
^] with PROCESS_DUP_HANDLE, and
DuplicateHandle[
^] after that.
2. NtQueryObject will hang if the handle points to named pipe (bug), so you should first try to run it in a new thread to check it, and only if the thread does not hand go on and use it in the main thread...
---
And...
There are some ready-made solutions out there, with source code:
HOWTO: Enumerate handles - Sysinternals Forums[
^]
Examine Information on Windows NT System Level Primitives[
^]