Jimmy Mattsson Jimmy Mattsson - 10 months ago 55
C# Question

Get users from an AD group

I have this code to work with users from a group

DirectorySearcher myGroupSearcher = new DirectorySearcher(myDirectoryEntry);
myGroupSearcher.Filter = String.Format("(&(objectClass=group)(|(cn={0})(dn={0})))", strGroupName);

SearchResult myGroupSearchResult = myGroupSearcher.FindOne();

if (myGroupSearchResult != null)
ResultPropertyValueCollection myUsersInGroup = myGroupSearchResult.Properties["member"];

int intMemberCount = myUsersInGroup.Count;

for (int i = 0; i < intMemberCount; i++)
//Split the current result
string[] strProperites = myUsersInGroup[i].ToString().Split(',');

//Get the CN
string strUsername = strProperites[0].Substring(3);

DirectorySearcher myUserSearcher = new DirectorySearcher(myDirectoryEntry);
myUserSearcher.Filter = String.Format("(&(objectClass=user)(|(cn={0})(sAMAccountName={0})))", strUsername);

SearchResult myUserSearchResult = myUserSearcher.FindOne();

//Do some work

This works for most users, but for some, the strUsername gets turncated depending on how the customers AD looks like (if the user have a CN containing ,). So this solution isnt the most optimal to use. Is there a way to get the samaccount name when searching for members in a group? Or is there a better way?

Answer Source
string[] strProperites = myUsersInGroup[i].ToString().Split(new string[] { "cn=" }, StringSplitOptions.RemoveEmptyEntries);