Question

I'm confused with following situation. My application attempts to find a specified directory:

HANDLE _dh, _fh; // Handles for a files
_dh = CreateFile(_ddn, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_DIRECTORY, NULL);

If directory does not exists application creates it:

if( _dh == INVALID_HANDLE_VALUE ) {
    if( GetLastError() == ERROR_FILE_NOT_FOUND){
        CreateDirectory( _ddn , NULL ); }
    else { 
        CStringW _err;
        DWORD _ed = GetLastError();
        _err.Format( L" ERROR# %u", _ed );
        MessageBox ( NULL , _err , L"123" , MB_OK );
        PostQuitMessage(0);
        return FALSE; 
    } 
}
CloseHandle(_dh);

This works but only first time. When directory already exists CreateFile fails with error #5: ACCESS DENIED even if app restarted.

Where is my mistake?

UPDATE

Just tried to create target folder manually - the same issue.

CreateFile( _ddn , GENERIC_READ , FILE_SHARE_READ | FILE_SHARE_WRITE , NULL , OPEN_EXISTING , FILE_ATTRIBUTE_DIRECTORY , NULL );

This call always invokes ERROR_ACCESS_DENIED error message (0x5 error code).

Was it helpful?

Solution

From MSDN:

To open a directory using CreateFile, specify the FILE_FLAG_BACKUP_SEMANTICS flag as part of dwFlagsAndAttributes.

So change to:

_dh = CreateFile( _ddn , GENERIC_READ , FILE_SHARE_READ | FILE_SHARE_WRITE , NULL , OPEN_EXISTING , FILE_FLAG_BACKUP_SEMANTICS , NULL );

instead.

Do not use FILE_ATTRIBUTE_DIRECTORY, it is not even documented.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top