2020年6月27日 星期六

【C#】Verify permission of specific directory

Actual verification of read permission to specific directory without opens a stream.

private static bool HasPermissionToReadFiles(string path)
{
    var readAllow = false;
    var readDeny = false;
    var firstFoundFile = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories).FirstOrDefault();
    if (firstFoundFile == null)
    {
        throw new Exception("There is no file in provided path.");
    }
    var accessControlList = Directory.GetAccessControl(firstFoundFile);
    if (accessControlList == null)
        return false;
    var accessRules = accessControlList.GetAccessRules(true, true, typeof(SecurityIdentifier));
    if (accessRules == null)
        return false;

    foreach (FileSystemAccessRule rule in accessRules)
    {
        if ((FileSystemRights.Read & rule.FileSystemRights) != FileSystemRights.Read) continue;

        if (rule.AccessControlType == AccessControlType.Allow)
            readAllow = true;
        else if (rule.AccessControlType == AccessControlType.Deny)
            readDeny = true;
    }

    return readAllow && !readDeny;
}


沒有留言:

張貼留言