Search code examples
c#asp.netactive-directorydirectoryentry

Get all users and contacts from a group in Active Directory


I have been searching around for a solution on getting both users and contacts from a group in Active Directory, but cant find one.

I understand that I cant get contacts the same way as users because they are not security principals?

I use this code to get all users in my group, is it possible to extend this to retrieve name, and mobile number from contacts? Or do I need to write something new?

            var context = new PrincipalContext(ContextType.Domain, "MY_DOMAIN");
            using (var searcher = new PrincipalSearcher())
            {
                var groupName = "MY_GROUP";
                var sp = new GroupPrincipal(context, groupName);
                searcher.QueryFilter = sp;
                var group = searcher.FindOne() as GroupPrincipal;

                if (group == null)
                    Console.WriteLine("Invalid Group Name: {0}", groupName);

                foreach (var f in group.GetMembers())
                {
                    var principal = f as UserPrincipal;

                    if (principal == null || string.IsNullOrEmpty(principal.Name))
                        continue;

                    DirectoryEntry entry = (principal.GetUnderlyingObject() as DirectoryEntry);
                    DirectorySearcher entrySearch = new DirectorySearcher(entry);
                    entrySearch.PropertiesToLoad.Add("mobile");
                    entrySearch.PropertiesToLoad.Add("sAMAccountName");
                    entrySearch.PropertiesToLoad.Add("name");
                    SearchResultCollection results = entrySearch.FindAll();

                    ResultPropertyCollection rpc = results[0].Properties;
                    foreach (string rp in rpc.PropertyNames)
                    {
                        if (rp == "mobile")
                            Console.WriteLine(rpc["mobile"][0].ToString());

                        if(rp == "sAMAccountName")
                            Console.WriteLine(rpc["sAMAccountName"][0].ToString());
                    }

Solution

  • You cannot use the System.DirectoryServices.AccountManagement namespace to query contact information from Active Directory because as you point out, they are not security principles. You'll need to read and parse the member property of the group directly from the group's DirectoryEntry. This will be a list of distinguished names of all the objects which are a member of the group. There's no way to know from this what kind of object they are so you'll need to query AD for each to find out.

    You have all the code needed to accomplish this already in what you posted, just add the member property to the load list and then loop though it loading new DirectoryEntry objects. The objectClass property will tell you if it's a user, group or contact.