如何在没有UAC的情况下从非管理员中检查管理员的写入权限

本文关键字:管理员 检查 权限 情况下 UAC | 更新日期: 2023-09-27 18:26:01

我正在尝试检查Admin是否对给定的文件夹具有写入权限。

它对当前用户运行良好,但我希望此方法能为Admin进程提供结果,因为稍后我将从当前模式转到Admin模式。只有在这个地方才需要这个检查。

这是我的winform应用程序的代码。

public static bool DirectoryCanCreate(string DirectoryPath)
    {
        if (string.IsNullOrEmpty(DirectoryPath)) return false;
        try
        {
            FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, DirectoryPath);
            if (!SecurityManager.IsGranted(writePermission))
            {
                return false;
            }
            AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            foreach (FileSystemAccessRule rule in rules)
            {
                if (identity.Groups.Contains(rule.IdentityReference))
                {
                    if ((FileSystemRights.Write & rule.FileSystemRights) == FileSystemRights.Write)
                    {
                        if (rule.AccessControlType == AccessControlType.Deny)
                            return false;
                        if (rule.AccessControlType == AccessControlType.Allow)
                            return true;
                    }
                }
            }
        }
        catch { 
        }
        return false;
    }

如何在没有UAC的情况下从非管理员中检查管理员的写入权限

您的代码当前获取当前用户标识,并且只检查该标识的权限。您应该更改它以检查其他用户的身份(在这种情况下是某些"管理员"帐户)。您可以通过调用WindowsIdentity.Impersonate(IntPtr); 来获取"Admin"用户的Identity对象

WindowsIdentity identity = WindowsIdentity.Impersonate(IntPtr OtherUserPtr);

但是,要获得IntPtr-OtherUserPtr值,您需要调用一些WinAPI代码。请查看此链接了解更多信息:https://msdn.microsoft.com/en-us/library/chf6fbt4(v=vs.110).aspx

或者,您可以更改GetAccessRulles()调用以获取typeof(System.Security.Principal.NTAccount),然后将字符串rule.IdentityReference.Value与所需的用户或组匹配。

更改:

AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));

对此:

AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

然后,当循环通过规则集合时,不要检查:

if (identity.Groups.Contains(rule.IdentityReference))

相反,请检查要检查的用户NT帐户名:

if( rule.IdentityReference.Value == @"BUILTIN'Administrators")