I have a shared folder. How do I check in C# whether the current user has been given access to the folder?
I have tried SecurityManager.IsGranted
but somehow it is not doing me any good. Probably because it is for a file, not for a folder.
I have a shared folder. How do I check in C# whether the current user has been given access to the folder?
I have tried SecurityManager.IsGranted
but somehow it is not doing me any good. Probably because it is for a file, not for a folder.
Use Directory.Exists
it will return false
if you don't have permission.
See the Remarks section in MSDN
Also as suggested in the answer by @jbriggs You should get an UnautorizedAccessException
if you don't have access.
If I recall correctly you have to just try to write something to the folder or read something from the folder and catch the exception.
Edit: you could do the following, however I'm not sure it works in every situation (like if permissions are allowed or denied for the users 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;
}