locked
Get process locking a file RRS feed

  • Question

  • Hi!

     

    I would like to know how to know which process is using a specific file. I can't access to the file and I would like to know how to get the name or the processId of the process using the file.

     

    To see if something else is currently using the file, I try to open it in read with no share:

    Code Snippet

    LPCTSTR lpszFile = FileOpenDialog.GetPathName();

    HANDLE hFile = CreateFile(lpszFile,

        GENERIC_READ,

        0,

        NULL,

        OPEN_EXISTING,

        FILE_ATTRIBUTE_NORMAL,

        NULL);

    if (hFile == INVALID_HANDLE_VALUE)

    {

        TRACE(_T("ERROR - failed to open %s\n"), lpszFile);

        return FALSE;

    }

     

    If hFile == INVALID_HANDLE_VALUE, then I assume that it is because the file was already being accessed. How can I be sure of that (it could always be some other error...)?

     

    Thanks a lot !

    Marie

    Monday, July 23, 2007 5:36 PM

Answers

  • To get more information, you would use GetLastError, immediately in

     

    if (hFile == INVALID_HANDLE_VALUE)

    {

        //check GetLastError here

        TRACE(_T("ERROR - failed to open %s\n"), lpszFile);

        return FALSE;

    }

     

    This will tell you windows error codes as to why the file could not be opened.

     

    I am not 100% sure, but I dont believe there is a way to tell what process has a particular file open.

    Monday, July 23, 2007 10:12 PM
  • It's not directly possible to know which process is using the given file, you will have to run through all the File Handles of all the processes. Following might help,

    http://www.codeguru.com/forum/showthread.php?t=176997

    Tuesday, July 24, 2007 7:24 AM

All replies

  • To get more information, you would use GetLastError, immediately in

     

    if (hFile == INVALID_HANDLE_VALUE)

    {

        //check GetLastError here

        TRACE(_T("ERROR - failed to open %s\n"), lpszFile);

        return FALSE;

    }

     

    This will tell you windows error codes as to why the file could not be opened.

     

    I am not 100% sure, but I dont believe there is a way to tell what process has a particular file open.

    Monday, July 23, 2007 10:12 PM
  • It's not directly possible to know which process is using the given file, you will have to run through all the File Handles of all the processes. Following might help,

    http://www.codeguru.com/forum/showthread.php?t=176997

    Tuesday, July 24, 2007 7:24 AM
  • Thanks Paul Marriott and Ramkrishna Pawar.

     

    Since parsing all processes is too long, I will just be getting the error code + string (using FormatMessage) as suggested by Ramkrishna.

    Tuesday, July 24, 2007 2:44 PM