Fast way to get a list of group members in Active Directory with C#

后端 未结 6 2077
时光取名叫无心
时光取名叫无心 2021-02-04 17:49

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 t

6条回答
  •  鱼传尺愫
    2021-02-04 18:24

    Try this not sure if it would be any faster but....

            PrincipalContext pcRoot = new PrincipalContext(ContextType.Domain)
    
            GroupPrincipal mygroup = new GroupPrincipal(pcRoot);
    
            // define the principal searcher, based on that example principal
    
            PrincipalSearcher ps = new PrincipalSearcher(mygroup);
    
            ps.QueryFilter = new GroupPrincipal(pcRoot) { SamAccountName = "Name of your group Case Sensitive" };
    
            List users = new List();
            // loop over all principals found by the searcher
    
            GroupPrincipal foundGroup = (GroupPrincipal)ps.FindOne();
    
    foreach (UserPrincipal u in foundGroup.Members) 
                        {
                            users.Add(u);
    
                        }
    //OR
    List lst = foundGroup.Members.Select(g => g.SamAccountName).ToList();//this will only get the usernames not the user object or UserPrincipal
    

提交回复
热议问题