I got a working solution, however I’m pretty sure there is a less resource-intensive method because the current solution involves doing a query to get the groups member and then a query to get each users information.
Here is the code I have :
DirectoryEntry root = new DirectoryEntry( "LDAP://server:port" );
DirectorySearcher searcher = new DirectorySearcher( root );
searcher.Filter = "(&(ObjectClass=Group)(CN=foo-group))";
var members = (IEnumerable)searcher.FindOne()
.GetDirectoryEntry()
.Invoke( "members" );
Dictionary<string , string> results = new Dictionary<string , string>();
foreach( object member in members ) {
DirectoryEntry de = new DirectoryEntry( member );
results.Add( de.Properties[ "SAMAccountname" ][ 0 ].ToString(), de.Properties[ "cn" ][ 0 ].ToString() );
}
Ideally I’d like to be able to do a single query to get every user that are member of a group, filters the properties to load and then display them. So something like this
DirectoryEntry root = new DirectoryEntry( "LDAP://server:port" );
DirectorySearcher searcher = new DirectorySearcher( root );
searcher.PropertiesToLoad.Add( "cn" );
searcher.PropertiesToLoad.Add( "SAMAccountname" );
searcher.Filter = "(&(ObjectClass=user)(memberof=foo-group))";
foreach( var user in searcher.FindAll() ) {
//do whatever...
}
Unfortunately, that doesn’t work for some reason.
If you can use
System.DirectoryServices.AccountManagement:I have some VB code that’ll do it the old way also, but this is definitely simpler with AccountManagement.
Here’s the VB code I was referring to (again it isn’t pretty but it’s functional):
And usage: