【问题标题】:C# Check if run as administrator [duplicate]C#检查是否以管理员身份运行[重复]
【发布时间】:2012-07-25 23:25:18
【问题描述】:

可能重复:
Check if the current user is administrator

我需要测试应用程序(用 C# 编写,运行 os Windows XP/Vista/7)是否以管理员身份运行(如右键单击 .exe -> 以管理员身份运行,或在兼容性选项卡中以管理员身份运行在属性下)。

我已经用谷歌搜索过 StackOverflow,但找不到可行的解决方案。

我最后一次尝试是这样的:

if ((new WindowsPrincipal(WindowsIdentity.GetCurrent()))
         .IsInRole(WindowsBuiltInRole.Administrator))
{
    ...
}

【问题讨论】:

  • 这是 UAC 的事情吗? IE。用户已经是管理员,但您想知道应用是否在 UAC 下提升?
  • 不是重复的。这个问题询问的是流程,而不是登录的用户。

标签: c# windows


【解决方案1】:

试试这个

public static bool IsAdministrator()
{
    var identity = WindowsIdentity.GetCurrent();
    var principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

这看起来与您的代码在功能上相同,但以上内容对我有用...

按功能执行,(没有不必要的临时变量)...

public static bool IsAdministrator()
{
   return (new WindowsPrincipal(WindowsIdentity.GetCurrent()))
             .IsInRole(WindowsBuiltInRole.Administrator);
}  

或者,使用表达式主体属性:

public static bool IsAdministrator =>
   new WindowsPrincipal(WindowsIdentity.GetCurrent())
       .IsInRole(WindowsBuiltInRole.Administrator);

【讨论】:

  • 确保包含“使用 System.Security.Principal;”
  • 在 Windows 10 上为我工作。
  • 您需要将其包装在 using 语句中:“using (var identity = WindowsIdentity.GetCurrent())”
  • 如果用户是管理员,这总是正确的。它不区分提升(以管理员身份运行,Microsoft 措辞不佳/令人困惑)。
  • 只有当用户是管理员并且运行提升的代码时才适用。在管理员命令提示符下,它将返回 true。在非管理员命令提示符下,它将返回 false。
猜你喜欢
  • 2020-07-31
  • 2010-12-22
  • 2021-08-28
  • 2016-12-11
  • 2011-04-02
  • 2017-09-15
  • 2015-01-27
  • 2015-02-06
  • 2020-05-05
相关资源
最近更新 更多