C#检查是否以管理员身份运行

ECl*_*son 57 c# windows

可能重复:
检查当前用户是否为管理员

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

我用Google搜索并搜索了StackOverflow,但我找不到可行的解决方案.

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

if ((new WindowsPrincipal(WindowsIdentity.GetCurrent()))
         .IsInRole(WindowsBuiltInRole.Administrator))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

Cha*_*ana 117

试试这个

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

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

在功能上做到这一点,(没有不必要的临时变量)......

public static bool IsAdministrator()
{
   return (new WindowsPrincipal(WindowsIdentity.GetCurrent()))
             .IsInRole(WindowsBuiltInRole.Administrator);
}  
Run Code Online (Sandbox Code Playgroud)

或者,使用表达体性质:

public static bool IsAdministrator =>
   new WindowsPrincipal(WindowsIdentity.GetCurrent())
       .IsInRole(WindowsBuiltInRole.Administrator);
Run Code Online (Sandbox Code Playgroud)

  • 确保包含"using System.Security.Principal;" (15认同)
  • 如果用户是管理员,则始终如此.它没有区分提升(以管理员身份运行,因此微软/混乱的措辞). (9认同)
  • 在 Windows 10 上为我工作。 (3认同)
  • 您需要将其包装在using语句中:“ using(var identity = WindowsIdentity.GetCurrent())” (2认同)
  • 仅当用户是管理员并运行提升的代码时,才会出现这种情况。在管理命令提示中,它将返回 true。在非管理员命令提示符下它将返回 false。 (2认同)