Using C#, how does one figure out what process locked a file?

前端 未结 9 1958
死守一世寂寞
死守一世寂寞 2020-11-22 13:03

In Windows, how do I determine (using C#) what process locked a file?

Third-party tools are helpful, but not what I\'m looking for.

9条回答
  •  名媛妹妹
    2020-11-22 13:54

    Not very straightforward, but on Windows Vista and above you can use the Restart Manager APIs to see who is using a file. Internet Explorer caches settings includes details on using this to detect which process has iexplore.exe open.

    Omitting a lot of detail:

    // Start an RM session
    RmStartSession(&sessionHandle, 0, sessionKey);
    
    // Register the file you are checking
    RmRegisterResources(sessionHandle, 1, filePathArray, 0, NULL, 0, NULL);
    
    // Get all processes that have that file open.
    RmGetList(sessionHAndle, &nProcInfoNeeded, &nProcInfo, processes, &rebootReason);
    RmEndSession(sessionHandle);
    

提交回复
热议问题