Fast way to get a list of group members in Active Directory with C#
Posted
by
Jeremy
on Stack Overflow
See other posts from Stack Overflow
or by Jeremy
Published on 2011-06-24T22:09:41Z
Indexed on
2011/06/25
0:22 UTC
Read the original article
Hit count: 452
In a web app, we're looking to display a list of sam accounts for users that are a member of a certain group. Groups could have 500 or more members in many cases and we need the page to be responsive.
With a group of about 500 members it takes 7-8 seconds to get a list of sam accounts for all members of the group. Are there faster ways? I know the Active Directory Management Console does it in under a second.
I've tried a few methods:
1)
PrincipalContext pcRoot = new PrincipalContext(ContextType.Domain)
GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcRoot, "MyGroup");
List<string> lst = grp.Members.Select(g => g.SamAccountName).ToList();
2)
PrincipalContext pcRoot = new PrincipalContext(ContextType.Domain)
GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcRoot, "MyGroup");
PrincipalSearchResult<Principal> lstMembers = grp.GetMembers(true);
List<string> lst = new List<string>();
foreach (Principal member in lstMembers )
{
if (member.StructuralObjectClass.Equals("user"))
{
lst.Add(member .SamAccountName);
}
}
3)
PrincipalContext pcRoot = new PrincipalContext(ContextType.Domain)
GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcRoot, "MyGroup");
System.DirectoryServices.DirectoryEntry de = (System.DirectoryServices.DirectoryEntry)grp.GetUnderlyingObject();
List<string> lst = new List<string>();
foreach (string sDN in de.Properties["member"])
{
System.DirectoryServices.DirectoryEntry deMember = new System.DirectoryServices.DirectoryEntry("LDAP://" + sDN);
lst.Add(deMember.Properties["samAccountName"].Value.ToString());
}
© Stack Overflow or respective owner