如果运行C#检查以管理员身份 [英] C# Check if run as administrator

查看:155
本文介绍了如果运行C#检查以管理员身份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:结果
检查当前用户是管理员






我需要测试应用程序(C#编写,运行操作系统Windows XP / VISTA / 7)以管理员身份运行(在右键单击.exe文件 - >以管理员身份运行,或在根据属性保持兼容标签管理员身份运行)。



我用Google搜索和搜索计算器,但我不能找到一个可行的解决方案。



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

 如果((新WindowsPrincipal(WindowsIdentity.GetCurrent()))IsInRole(WindowsBuiltInRole.Administrator))
{

}


解决方案

试试这个

 公共静态布尔IsAdministrator()
{
变种标识=的WindowsIdentity。 GetCurrent();
变种本金=新的WindowsPrincipal(身份);
返回principal.IsInRole(WindowsBuiltInRole.Administrator);
}

这看起来功能也可以通过你的代码,但上面为我工作...



做功能上,(没有不必要的临时变量)...

 公共静态布尔IsAdministrator()
{
返回(新WindowsPrincipal(WindowsIdentity.GetCurrent()))
.IsInRole(WindowsBuiltInRole.Administrator);
}


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).

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

My last attempt was this:

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

解决方案

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);
    }       

这篇关于如果运行C#检查以管理员身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆