在.NET / C#测试,如果过程中有管理权限 [英] In .NET/C# test if process has administrative privileges

查看:235
本文介绍了在.NET / C#测试,如果过程中有管理权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有规范的方法进行测试,看看如果这个过程在计算机上具有管理权限?

Is there a canonical way to test to see if the process has administrative privileges on a machine?

我将要开始一个长期运行的进程,以及后来很多在这个过程中的存留时间它会尝试一些事情,需要管理员权限。

I'm going to be starting a long running process, and much later in the process' lifetime it's going to attempt some things that require admin privileges.

我希望能够测试前面如果进程有这些权利,而不是以后。

I'd like to be able to test up front if the process has those rights rather than later on.

推荐答案

这将检查如果用户是本地Administrators组中(假设你不检查域管理员权限)

This will check if user is in the local Administrators group (assuming you're not checking for domain admin permissions)

using System.Security.Principal;

public bool IsUserAdministrator()
{
    //bool value to hold our return value
    bool isAdmin;
    WindowsIdentity user = null;
    try
    {
        //get the currently logged in user
        user = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(user);
        isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch (UnauthorizedAccessException ex)
    {
        isAdmin = false;
    }
    catch (Exception ex)
    {
        isAdmin = false;
    }
    finally
    {
        if (user != null)
            user.Dispose();
    }
    return isAdmin;
}

这篇关于在.NET / C#测试,如果过程中有管理权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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