How do I check if a folder is available?

I have a shared folder. How can I check in C # if the current user has been granted access to a folder?

I tried SecurityManager.IsGranted

it but somehow it doesn't do me any good. Probably because it is for a file, not a folder.

+3


source to share


2 answers


Use Directory.Exists

it will return false

if you don't have permission.

See the Notes section on MSDN



Also as suggested in @ jbriggs answer you should get UnautorizedAccessException

if you don't have access.

+5


source


If I remember correctly, you just have to try to write something to the folder or read something from the folder and catch the exception.

Edit: You can do the following, however I'm not sure if it works in every situation (for example if permissions are allowed or denied for a user group)



public bool HasAccess(string path, string user)
{
System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
System.Security.Principal.NTAccount acct = sid.Translate(typeof(System.Security.Principal.NTAccount)) as System.Security.Principal.NTAccount;
bool userHasAccess = false;
if( Directory.Exists(path))
{
  DirectorySecurity sec = Directory.GetAccessControl(path);
  AuthorizationRuleCollection rules = sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
  foreach (AccessRule rule in rules)
  {
    // check is the Everyone account is denied
    if (rule.IdentityReference.Value == acct.ToString() && 
        rule.AccessControlType == AccessControlType.Deny)
    {
      userHasAccess = false;
      break;
    }
    if (rule.IdentityReference.Value == user)
    {
      if (rule.AccessControlType != AccessControlType.Deny)                 
        userHasAccess = true;
      else
        userHasAccess = false;
      break;
    }
  }
}
return userHasAccess;
}            

      

-1


source







All Articles