5

我的本地用户帐户在管理员组中,我想简单地弄清楚 Windows 窗体项目如何确定我是否在管理员组中。所以,我开始了一个 Windows 窗体项目并尝试了以下方法:

[STAThread]
static void Main()
{
    string adminGroup1 = @"BUILTIN\Administrators";
    string adminGroup2 = Environment.MachineName + @"\Administrators";
    string adminGroup3 = Environment.MachineName.ToLower() + @"\Administrators";
    string adminGroup4 = "Administrators";
    string adminGroup5 = "administrators";

    AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
    WindowsPrincipal currentUser1 = (WindowsPrincipal)Thread.CurrentPrincipal;
    bool IsAdmin1_1 = currentUser1.IsInRole(adminGroup1); // false
    bool IsAdmin1_2 = currentUser1.IsInRole(adminGroup2); // false
    bool IsAdmin1_3 = currentUser1.IsInRole(adminGroup3); // false
    bool IsAdmin1_4 = currentUser1.IsInRole(adminGroup4); // false
    bool IsAdmin1_5 = currentUser1.IsInRole(adminGroup5); // false

    WindowsPrincipal currentUser2 = new WindowsPrincipal(WindowsIdentity.GetCurrent());
    bool IsAdmin2_1 = currentUser2.IsInRole(adminGroup1); // false
    bool IsAdmin2_2 = currentUser2.IsInRole(adminGroup2); // false
    bool IsAdmin2_3 = currentUser2.IsInRole(adminGroup3); // false
    bool IsAdmin2_4 = currentUser1.IsInRole(adminGroup4); // false
    bool IsAdmin2_5 = currentUser2.IsInRole(adminGroup5); // false

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

为什么上述所有检查都失败了?

4

1 回答 1

5

尝试

currentUser1.IsInRole(WindowsBuiltInRole.Administrator)

请参阅MSDN

“在 Windows Vista 和更高版本的 Windows 操作系统中,用户帐户控制 (UAC) 确定用户的权限。[..] 执行 IsInRole 方法的代码不显示同意对话框。如果代码返回 false您是标准用户角色,即使您在内置管理员组中”

于 2012-02-16T11:10:47.727 回答