List local Windows Administator names with .NET

List local Windows Administator names with .NET

First, you need to install the NuGet Package System.DirectoryServices.AccountManagement

Now you can open a context and get all members of the built-in group "Administrators"

// This works only on Windows!
using System.DirectoryServices.AccountManagement;
using (PrincipalContext ctx = new PrincipalContext(ContextType.Machine))
using (GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, "Administrators"))
{
    if (grp is not null)
    {
        Console.WriteLine("Output:");
        foreach (Principal p in grp.GetMembers(recursive: true))
        {
            Console.WriteLine(p.Name);
        }
    }
}

Result:

Output:
Ben
Administrator