Check if the current user is administrator

My application needs to run some scripts, and I must be sure that the user running them is an administrator... What is the best way of doing this using C#?


Solution 1:

using System.Security.Principal;

public static bool IsAdministrator()
{
    using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
    {
        WindowsPrincipal principal = new WindowsPrincipal(identity);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
}

Solution 2:

return new WindowsPrincipal(WindowsIdentity.GetCurrent())
    .IsInRole(WindowsBuiltInRole.Administrator);

Solution 3:

You can also call into the Windows API to do this:

[DllImport("shell32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsUserAnAdmin();

which more generically tells you whether user is running under elevated rights.