This is what I try:
public List<string> GetUsersInGroup(string domain, string group)
{
List<string> groupMemebers = new List<string>();
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain);
DirectorySearcher groupSearch = new DirectorySearcher(entry);
groupSearch.Filter = "(&(objectclass=group)(samaccountname=" + group +"))";
groupSearch.PropertiesToLoad.Add("DistinguishedName");
SearchResult srG = groupSearch.FindOne();
String DN = srG.Properties["DistinguishedName"][0].ToString();
entry.RefreshCache(new string[] { "memberOf" });
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = "(|(&(objectClass=computer)(memberOf=" + DN + "))(&(objectClass=User)(memberOf=" + DN + ")))";
SearchResultCollection srcg = mySearcher.FindAll();
foreach (SearchResult resEnt in srcg)
{
groupMemebers.Add(resEnt.GetDirectoryEntry().Name.ToString());
}
return groupMemebers;
}
Edit:
It’s good to find USERS belong the group but I can get the Computers (memberOF) the group if group is “Domain Computers” or “Domain Controllers” (primary Groups!).
Some one can help me?
The primary group of an object (user or computer) in AD is stored in a property called “primaryGroupID”. For example, for users this is generally 513, which means that the primary group is “Domain Users”.
The built-in groups (Domain Users, Domain Computers etc) have many members, and storing the membership in the usual way through the “member” property would cause performance issues. This is why you don’t see “Domain Computers” in the memberof property.
Basically, if you want to find computers that are members of “Domain Computers”, you must run the query
Check How to use the PrimaryGroupID attribute to find the primary group for a user – this applies also to computers.
Also check Well-known security identifiers in Windows operating systems