Search code examples
c#active-directorydirectoryentry

Getting users from an Active Directory group


I have been banging my head for hours trying to figure out why this wont' work. I found an example of getting a list of users from an AD group but I can't get it to work. Here is what I've been trying to do:

DirectoryEntry de = new DirectoryEntry("LDAP://DC=" + domain + ",DC=com");

DirectorySearcher ds = new DirectorySearcher(de);//, "(objectClass=person)");

ds.Filter = "(&(objectCategory=person)(objectclass=user)(memberOf=CN=!CityNameGroup))"; 

ds.PropertiesToLoad.Add("givenname");
ds.PropertiesToLoad.Add("samaccountname");
ds.PropertiesToLoad.Add("sn");
ds.PropertiesToLoad.Add("useraccountcontrol");

foreach (SearchResult sr in ds.FindAll())
{//stuff goes here}

but ds.FindAll always brings back 0 results with this filter. I can do simpler filters that bring back results, but I never get anything back from the above filter. I just want all my users that are in the !CityNameGroup. I appreciate the help!


Solution

  • If .NET 3.5 is an option, stop banging your head and look here:

    Everything in Active Directory via C#.NET 3.5 (Using System.DirectoryServices.AccountManagement)

    Seriously, AD handling in .NET 3.5 is another world. It will change everything. For the better, of course.

    Update

    Also, there's a ready answer here ( Active Directory User Group Memberships GroupPrincipal ). I will have the decency of not copying it. :)

    It uses .NET 3.5, BTW.