Check if the current user is administrator

Viewed 52602

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#?

9 Answers

Like others here, my program is not running elevated, so this code returns false if UAC is enabled:

private bool IsCurrentUserAnAdmin()
{
    var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

@EricBDev's answer with IsAdministratorNoCache does return true if my program is not running elevated, and the user is an Admin. However, like the blog author says, it is very slow.

Here is my solution; it emulates IsAdministratorNoCache but is fast:

private bool IsCurrentUserInAdminGroup()
{
    // https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/security-identifiers-in-windows
    // S-1-5-32-544
    // A built-in group. After the initial installation of the operating system,
    // the only member of the group is the Administrator account.
    // When a computer joins a domain, the Domain Admins group is added to
    // the Administrators group. When a server becomes a domain controller,
    // the Enterprise Admins group also is added to the Administrators group.
    var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
    var claims = principal.Claims;
    return (claims.FirstOrDefault(c => c.Value == "S-1-5-32-544") != null);
}

The answer by David Ching is good - but leaves you with a hardcoded ID for the Admin group. This is a bit clearer:

private bool IsCurrentUserInAdminGroup()
{
    var claims = new WindowsPrincipal(WindowsIdentity.GetCurrent()).Claims;
    var adminClaimID = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Value;
    return claims.Any(c => c.Value == adminClaimID);
}

This is how I end up... I'm forcing my app to run as administrator mode. To do this

1- Add <ApplicationManifest>app.manifest</ApplicationManifest> to your csproj file.

MyProject.csproj

<Project Sdk="Microsoft.NET.Sdk">    
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <ApplicationManifest>app.manifest</ApplicationManifest>
  </PropertyGroup>    
</Project>

2- Add the below app.manifest file to your project.

app.manifest

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>
Related