Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 499
Tomáš Zato - Reinstate Monica Avatar asked Oct 15 '25 18:10

Tomáš Zato - Reinstate Monica


1 Answers

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.

like image 112
MARSHMALLOW Avatar answered Oct 18 '25 11:10

MARSHMALLOW



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!