2012-07-25 39 views
43

可能重复:
Check if the current user is administratorC#检查以管理员身份运行

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

我已经Google和搜索StackOverflow,但我找不到工作的解决方案。

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

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

这是一个UAC的事情吗?即用户已经是管理员,但是你想知道在UAC下应用程序是否升级? – spender 2012-07-25 23:32:04

+2

不重复。这个问题是关于这个过程,而不是关于登录的用户。 – 2016-03-16 08:30:32

回答

79

试试这个

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); 
+13

确保包含“using System.Security.Principal;” – LightLabyrinth 2013-01-22 16:02:43

+0

在Windows 10上为我工作。 – Alexander 2017-09-16 08:42:07

+0

您需要将它封装在using语句中:“using(var identity = WindowsIdentity.GetCurrent())” – zezba9000 2018-01-01 22:59:22

相关问题