在.NET / C#测试,如果过程中有管理权限中有、管理权限、过程、测试

2023-09-02 10:20:02 作者:青瓷。

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

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