public static bool CheckPermissions(WindowsIdentity user, string path, FileSystemRights expectedRights)
{
var fi = new FileInfo(path);
var di = new DirectoryInfo(path);
AuthorizationRuleCollection acl;
if (fi.Exists)
{
acl = fi.GetAccessControl().GetAccessRules(true, true, typeof (SecurityIdentifier));
}
else if (di.Exists)
{
acl = di.GetAccessControl().GetAccessRules(true, true, typeof (SecurityIdentifier));
}
else
{
return false;
}
// gets rules that concern the user and his groups
IEnumerable<AuthorizationRule> userRules = from AuthorizationRule rule in acl
where user.Groups != null && user.User != null && (user.User.Equals(rule.IdentityReference)
|| user.Groups.Contains(rule.IdentityReference))
select rule;
FileSystemRights denyRights = 0;
FileSystemRights allowRights = 0;
// iterates on rules to compute denyRights and allowRights
foreach (FileSystemAccessRule rule in userRules)
{
if (rule.AccessControlType.Equals(AccessControlType.Deny))
{
denyRights = denyRights | rule.FileSystemRights;
}
else if (rule.AccessControlType.Equals(AccessControlType.Allow))
{
allowRights = allowRights | rule.FileSystemRights;
}
}
allowRights = allowRights & ~denyRights;
// are rights sufficient?
return (allowRights & expectedRights) == expectedRights;
}