qdii
qdii

Reputation: 12953

CreateFileA fails with ERROR_ACCESS_DENIED

I need to retrieve a handle to a directory to be able to call ReadDirectoryChangesW on it. Actually I would need a bit more than that but let’s go easy first. I have narrowed down the problem to this:

m_directoryHandle = CreateFileA(
    "C:\\Users\\victor\\Documents\\Projets\\libxnotify\\unittests", // __in      LPCTSTR lpFileName,
    FILE_LIST_DIRECTORY,    // __in      DWORD dwDesiredAccess,
    0,                      // __in      DWORD dwShareMode,
    0,                      // __in_opt  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
    OPEN_EXISTING,          // __in      DWORD dwCreationDisposition,
    0,                      // __in      DWORD dwFlagsAndAttributes,
    0                       // __in_opt  HANDLE hTemplateFile
);

This return an INVALID_HANDLE_VALUE with a last error code of ERROR_ACCESS_DENIED. Needless to say, I have tried oodles of different parameters, none on them did work. I run my program as victor, and to make sure I really had the rights in that unittests directory, I opened a command shell and typed:

C:\Users\victor>echo bla >> "C:\Users\victor\Documents\Projets\libxnotify\unittests\test"

and it worked.

Upvotes: 1

Views: 1673

Answers (1)

AusCBloke
AusCBloke

Reputation: 18492

The documentation for ReadDirectoryChangesW has a remark that states:

To obtain a handle to a directory, use the CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag.

The documentation for CreateFile then also has a more detailed remark about this:

Directories

An application cannot create a directory by using CreateFile, therefore only the OPEN_EXISTING value is valid for dwCreationDisposition for this use case. To create a directory, the application must call CreateDirectory or CreateDirectoryEx.

To open a directory using CreateFile, specify the FILE_FLAG_BACKUP_SEMANTICS flag as part of dwFlagsAndAttributes. Appropriate security checks still apply when this flag is used without SE_BACKUP_NAME and SE_RESTORE_NAME privileges.

You're missing out on this important FILE_FLAG_BACKUP_SEMANTICS flag for dwFlagsAndAttributes.

Upvotes: 4

Related Questions