I've the following code to query AD using DirectorySearcher
to get all the AD groups for a user.
List<string> Groups = new List<string>();
//initialize the directory entry object
DirectoryEntry dirEntry = new DirectoryEntry(ldapPath);
//directory searcher
DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry);
//enter the filter
dirSearcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", username);
//get the member of properties for the search result
dirSearcher.PropertiesToLoad.Add("memberOf");
int propCount;
SearchResult dirSearchResults = dirSearcher.FindOne();
propCount = dirSearchResults.Properties["memberOf"].Count;
string dn;
int equalsIndex;
int commaIndex;
for (int i = 0; i <= propCount - 1; i++)
{
dn = dirSearchResults.Properties["memberOf"][i].ToString();
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if (equalsIndex == -1)
{
return null;
}
if (!Groups.Contains(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1)))
{
Groups.Add(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
}
}
return Groups;
But when i check the 'memberof' tab in AD for a user I've one additional group 'Domain Users' which I'm not getting through this code.
Any ideas? Why I'm not getting 'Domain Users' in the 'memberof' collection?
Groups can be members of other groups. Maybe your users are not direct members, but only indirect members?
I do iterate all groups for child groups, too, when retrieving the groups on an AD.
Be warned that you may get endless recursion, since groups can (indirectly) contain each other. I had a hard time finding this out :-( Now I remember each processed group in a "global" list to only process it once to avoid this).
I've written a CodeProject article with some general purpose libraries, that contains AD classes, too. (See the classes in the " /Tools/DirectoryServices/
" sub folder in the downloaded ZIP file).
This is old, but for anyone else searching, the reason that the memberof attribute was missing "Domain Users" is because that was the AD object's PRIMARY GROUP. To find a user's primary group, you need to:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.