In .NET/C# test if process has administrative privileges

前端 未结 10 1971
天涯浪人
天涯浪人 2020-11-27 03:35

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

10条回答
  •  無奈伤痛
    2020-11-27 04:30

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

提交回复
热议问题