Tomáš Zato
Tomáš Zato

Reputation: 53139

CreateFile always returns error 5 (Access is denied) when trying to open directory for reading

I want to open directory handle so that I can watch that directory for file changes. I have written a simple class wrapper over the winapi, and this is how I set the directory path before starting the watch:

bool SetDirectory(const std::string& dirname)
{
  HANDLE dirHandleNew = CreateFile(
    dirname.c_str(),
    // Just normal reading
    FILE_GENERIC_READ,
    // Share all, do not lock the file
    FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,
    NULL,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    NULL
  );

  if (INVALID_HANDLE_VALUE != dirHandleNew)
  {
    _dirHandle = dirHandleNew;
    return true;
  }
  else
  {
    _dirHandle = 0;
    RLog("Cannot open directory %s for filesystem watching. Win error: %d (%s)", dirname.c_str(), GetLastError(), GetLastErrorAsString().c_str());
    return false;
  }
}

The error is always:

Cannot open directory D:\tools for filesystem watching. Win error: 5 (Access is denied.)

I tried different folders on different volumes to see if this is an actual permissions issue, but it doesn't seem like it. D:\tools in my PC is a normal folder, accessible to all users. But as I said, I tried other folders too, error is always the same.

I also tried to instead open with FILE_LIST_DIRECTORY (I only need dir listing) and GENERIC_READ. Error was still the same.

Maybe the CreateFile parameters are wrong?

Upvotes: 3

Views: 6685

Answers (1)

MARSHMALLOW
MARSHMALLOW

Reputation: 1395

Don't use FILE_ATTRIBUTE_NORMAL!

To open a directory with CreateFile, Use FILE_FLAG_BACKUP_SEMANTICS instead of FILE_ATTRIBUTE_NORMAL.

You should specify FILE_FLAG_BACKUP_SEMANTICS in the dwFlagsAndAttributes parameter.

This should work now.

Upvotes: 5

Related Questions