Bharat Singh
Bharat Singh

Reputation: 161

Need to check if folder has Read and Execute permissions in c# and it should fails when the user has only List contents permissions

I tried checking the permissions of directory which has only List folder contents permissions for the current user but still it returns true for the below piece of code.

        WindowsIdentity currentuser = WindowsIdentity.GetCurrent();
        var domainAndUser = currentuser.Name;
        DirectoryInfo dirInfo = new DirectoryInfo(downloadSource.BasePath);
        DirectorySecurity dirAC = dirInfo.GetAccessControl(AccessControlSections.All);
        AuthorizationRuleCollection rules = dirAC.GetAccessRules(true, true, typeof(NTAccount));
        foreach(AuthorizationRule rule in rules)
        {
          if (rule.IdentityReference.Value.Equals(domainAndUser, StringComparison.CurrentCultureIgnoreCase))
                {
                        if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.ReadAndExecute) > 0 )
                        return true;
                }
        }
        return false;

Upvotes: 1

Views: 813

Answers (1)

grek40
grek40

Reputation: 13438

Seems to be a simple bit logic error

Suppose you have flags

read = 1
execute = 2
ReadAndExecute = 3

and result

FileSystemRights = 1 (read only, no execute)

then

((FileSystemRights & ReadAndExecute) > 0) is true

So try the following check instead:

if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.ReadAndExecute) == FileSystemRights.ReadAndExecute)

It will check that not any but all flags from ReadAndExecute are required.

Alternative, use the enum flag check:

if ((((FileSystemAccessRule)rule).FileSystemRights).HasFlag(FileSystemRights.ReadAndExecute))

Upvotes: 1

Related Questions