C# – Get List of Users From Active Directory In A Given AD Group


I have code that searches for all users in a department:

string Department = "Billing";
DirectorySearcher LdapSearcher = new DirectorySearcher();
LdapSearcher.Filter = string.Format("(&(objectClass=user)(department={0}))", Department);
SearchResultCollection src = LdapSearcher.FindAll();

What would the filter need to look like if I only wanted everyone in the "Manager Read Only" AD Group?

Am I going about this all wrong?

Best Solution

Looking at your search I have a couple of points for you. First, the search uses objectClass (non-indexed) instead of objectCategory (indexed). Huge performance issue with that query. You would most always want to combine the two together depending on what you are trying to retrieve:

(&(objectCategory=person)(objectClass=user)) = All users (no contacts)
(&(objectCategory=person)(objectClass=contact)) = All contacts (no users)
(&(objectCategory=person)) = All users and contacts

As for looking up the users in a group you can enumerate the list of member objects of the specific group. In the member attribute of the group object is the distinguishedName of each user.

This article describes enumerating members of a group...

Don't forget that you may have to handle nested groups of the parent group, as there isn't a default way to handle this with LDAP queries. For that you may need to evaluate if the member object is a group and then get the member attribute for that child group.

Lastly, you should get in the habit of specifying a dns prefix to your query.

Without DNS prefix:


With DNS prefix (all three work):


A single domain won't cause you much issue but when you try and run a search in a multiple domain environment you will get bitten without this addition. Hope this helps move you closer to your goal.