3

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).

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
Geradlus_RU
  • 1,466
  • 2
  • 20
  • 37

1 Answers1

4

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.

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
  • This is something unreal! I've read [this page](http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx) dozen times, but didn't saw about FILE_FLAG_BACKUP_SEMANTICS. Moreover all the stuff my app does is data backup! Thank you man! – Geradlus_RU Nov 13 '12 at 23:34
  • FILE_ATTRIBUTE_DIRECTORY is usually used with the FindFirstFile/FindNextFile/FindClose triple. – kol Nov 13 '12 at 23:37
  • @kol yes, I use this attribute in my file copy routine to check if current file in loop is not a directory. – Geradlus_RU Nov 13 '12 at 23:43