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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11660184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:42:02  来源:igfitidea点击:

C# Check if run as administrator

c#windows

提问by EClaesson

Possible Duplicate:
Check if the current user is administrator

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

I need to test if the application (written in C#, running os Windows XP/Vista/7) is running as administrator (as in right-click .exe -> Run as Administrator, or Run as Administrator in the Compability tab under Properties).

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

I have googled and searched StackOverflow but i can not find a working solution.

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

My last attempt was this:

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

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

采纳答案by Charles Bretana

Try this

尝试这个

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

This looks functionally the same as your code, but the above is working for me...

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

doing it functionally, (without unnecessary temp variables) ...

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

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

or, using expression-bodied property:

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

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