MTS
MTS

Reputation: 114

c# How to list all windows users ( especially domain accounts )

I need to list all windows users in C#

This is my code:

var usersSearcher = new ManagementObjectSearcher( @"SELECT * FROM Win32_UserAccount" );
var users         = usersSearcher.Get();

Unfortunately this code didn't return domain accounts, why?

Upvotes: 1

Views: 545

Answers (1)

Mykyta Halchenko
Mykyta Halchenko

Reputation: 798

static void Main(string[] args)
{
    string groupName = "Domain Users";
    string domainName = "";
 
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName);
    GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupName);
 
    if (grp != null)
    {
         foreach (Principal p in grp.GetMembers(false))
            {
                Console.WriteLine(p.SamAccountName + " - " + p.DisplayName);
            }
 
 
        grp.Dispose();
        ctx.Dispose();
        Console.ReadLine();
    }
    else
    {
        Console.ReadLine();
    }
}

Try something like this

Upvotes: 1

Related Questions