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

.net, c#, security, windows

Solution

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

Problem

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.

Original source