【问题标题】:Why is WindowsPrincipal.IsInRole always returning false for the "Administrators" group?为什么 WindowsPrincipal.IsInRole 总是为“管理员”组返回 false?
【发布时间】:2012-03-07 18:48:57
【问题描述】:

我的本​​地用户帐户在管理员组中,我想简单地弄清楚 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());
}

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

【问题讨论】:

  • 您使用的是英文 Windows 版本吗?否则,您必须为“Administrators”组指定本地化名称。
  • UAC 已开启,所以在提示之前您不是管理员?以管理员身份运行你的代码来证明。
  • @TonyHopkinson 你是对的。以提升的权限启动 VS 后,检查工作正常。

标签: c# winforms windows-principal


【解决方案1】:

试试

currentUser1.IsInRole(WindowsBuiltInRole.Administrator)

MSDN

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

【讨论】:

  • 这仍然是假的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多