可能重复:
检查当前用户是否为管理员
我需要测试应用程序(用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)