private void GetAccountAccessRights(
string path,
SecuredObject objectToSecure,
Dictionary<string, SecuredObjectAccessRights> read,
Dictionary<string, SecuredObjectAccessRights> write,
Dictionary<string, SecuredObjectAccessRights> configure)
{
AuthorizationRuleCollection authorizationRules = null;
// determine if a file or directory.
FileInfo fileInfo = new FileInfo(path);
if (fileInfo.Exists)
{
FileSystemSecurity security = fileInfo.GetAccessControl(AccessControlSections.Access);
authorizationRules = security.GetAccessRules(true, true, typeof(NTAccount));
}
else
{
DirectoryInfo directoryInfo = new DirectoryInfo(path);
if (directoryInfo.Exists)
{
FileSystemSecurity security = directoryInfo.GetAccessControl(AccessControlSections.Access);
authorizationRules = security.GetAccessRules(true, true, typeof(NTAccount));
}
}
// check if no rules to add.
if (authorizationRules == null || authorizationRules.Count == 0)
{
return;
}
// process the access rules.
for (int ii = 0; ii < authorizationRules.Count; ii++)
{
// check for file system rule.
FileSystemAccessRule accessRule = authorizationRules[ii] as FileSystemAccessRule;
if (accessRule == null)
{
continue;
}
// check the type of rule.
bool denied = (accessRule.AccessControlType == System.Security.AccessControl.AccessControlType.Deny);
// check for right to take ownership.
if (!denied)
{
if ((FileSystemRights.TakeOwnership & accessRule.FileSystemRights) != 0)
{
UpdateAccessRightSet(objectToSecure, accessRule.IdentityReference, denied, configure);
}
}
// check if the rule affects configuration rights.
if ((FileSystemRights.ChangePermissions & accessRule.FileSystemRights) != 0)
{
UpdateAccessRightSet(objectToSecure, accessRule.IdentityReference, denied, configure);
}
// check if the rule affects write rights.
if ((FileSystemRights.WriteData & accessRule.FileSystemRights) != 0)
{
UpdateAccessRightSet(objectToSecure, accessRule.IdentityReference, denied, write);
}
// check if the rule affects read rights.
if ((FileSystemRights.ReadData & accessRule.FileSystemRights) != 0)
{
UpdateAccessRightSet(objectToSecure, accessRule.IdentityReference, denied, read);
}
// check if the rule affects read rights.
if (objectToSecure == SecuredObject.ExecutableFile)
{
if ((FileSystemRights.ExecuteFile & accessRule.FileSystemRights) != 0)
{
UpdateAccessRightSet(objectToSecure, accessRule.IdentityReference, denied, read);
}
}
else
{
if ((FileSystemRights.ReadData & accessRule.FileSystemRights) != 0)
{
UpdateAccessRightSet(objectToSecure, accessRule.IdentityReference, denied, read);
}
}
}
}