List users in Active Directory with C#

10. January 2012 15:07 by Mrojas in   //  Tags: , ,   //   Comments (0)
If you ever need to list the user in a domain. For example Artinsoft.com this is code might be helpful

public static void Main()
    {
        var ctx = new PrincipalContext(ContextType.Domain,"Artinsoft",
                                            "DC=artinsoft,DC=com");
        UserPrincipal userPrin = new UserPrincipal(ctx);
        userPrin.Name = "*";
        var searcher = new System.DirectoryServices.AccountManagement.PrincipalSearcher();
        searcher.QueryFilter = userPrin;
        var results = searcher.FindAll();
        foreach (Principal p in results)
        {
            Console.WriteLine("Name:{0},Account={1},DisplayName={2},Distinguish={3}",
p.Name,
p.SamAccountName,
p.DisplayName,
p.DistinguishedName); } }

Categories