When attempting to open a path with CreateFileW, does ERROR_ACCESS_DENIED always indicate that the file exists?

Issue

When using CreateFileW with OPEN_EXISTING it can sometimes fail with ERROR_ACCESS_DENIED. As far as I’m aware this always means the file exists but that you can’t open it for whatever reason. However, are there any cases where it could fail with ERROR_ACCESS_DENIED but the file does not exist?

Solution

in general – yes. ERROR_ACCESS_DENIED on CreateFileW call mean that file or folder exist. however the source of error – was NTSTATUS code, which than converted to win32 code. problem here that frequently multiple different NTSTATUS converted to single win32 error code. especially for ERROR_ACCESS_DENIED ( not less that 25 different status converted to single code 5 – ERROR_ACCESS_DENIED). for get source NTSTATUS better call native api direct or RtlGetLastNtStatus() in place (or together) GetLastError.

for example CreateFileW call NtCreateFile with FILE_NON_DIRECTORY_FILE option usually (if you not set FILE_FLAG_BACKUP_SEMANTICS flag) and if with given name exist folder (directory) – status STATUS_FILE_IS_A_DIRECTORY will be returned. of course this by sense have nothing common with access denied, but will be converted to ERROR_ACCESS_DENIED .

special (undocumented) system api:

NTSYSAPI BOOLEAN NTAPI RtlDoesFileExists_U ( _In_ PWSTR FileName )

believes that the file exists if get STATUS_ACCESS_DENIED status (note that STATUS_ACCESS_DENIED not equal ERROR_ACCESS_DENIED) on file (after call ZwQueryAttributesFile), so i think will be enough correct do the same (but check for status instead win32 error).

in the end of end here always exist race condition by design. even if api exactly return to you that file exist – at the time when you got this code – file may be already deleted. or visa versa. so question – for what this need at all.

Answered By – RbMm

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published