Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file is being used by another application?

Tags:

c

winapi

I am using the following code to check if a file is being used by another application:

HANDLE fh = CreateFile("D:\\1.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE)
{
    MessageBox(NULL, "The file is in use", "Error", 0);
}

If the file is being used by another application, the message box is displayed. However, the message box is also displayed if the file does not exists!

So what should I do to solve this problem, should I also check if the file exists (using another function), or can the parameters of CreateFile() be changed to only return INVALID_HANDLE_VALUE if the file is in use and does exists?

like image 484
James Avatar asked Dec 05 '25 14:12

James


1 Answers

If you wish to find out, which process has a file open, use the Restart Manager. The procedure consists of the following steps (as outlined in Raymond Chen's blog entry How do I find out which process has a file open?):

  1. Create a Restart Manager session (RmStartSession).
  2. Add a file resource to the session (RmRegisterResource).
  3. Ask for a list of all processes affected by that resource (RmGetList).
  4. Close the session (RmEndSession).


Sample code:
#include <Windows.h>
#include <RestartManager.h>
#pragma comment(lib, "Rstrtmgr.lib")

bool IsFileLocked( const wchar_t* PathName ) {
    bool isFileLocked = false;

    DWORD dwSession = 0x0;
    wchar_t szSessionKey[CCH_RM_SESSION_KEY + 1] = { 0 };
    if ( RmStartSession( &dwSession, 0x0, szSessionKey ) == ERROR_SUCCESS ) {
        if ( RmRegisterResources( dwSession, 1, &PathName,
                                  0, NULL, 0, NULL ) == ERROR_SUCCESS ) {
            DWORD dwReason = 0x0;
            UINT nProcInfoNeeded = 0;
            UINT nProcInfo = 0;
            if ( RmGetList( dwSession, &nProcInfoNeeded,
                            &nProcInfo, NULL, &dwReason ) == ERROR_MORE_DATA ) {
                isFileLocked = ( nProcInfoNeeded != 0 );
            }
        }
        RmEndSession( dwSession );
    }

    return isFileLocked;
}
like image 53
IInspectable Avatar answered Dec 07 '25 06:12

IInspectable



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!