none
C#.NET Add User to Group and check pre-existing membership in Active Directory

    Question

  • I have a C# method to add a user to a group in Active Directory whilst first checking there existing group membership to make sure they're not already a member of the group. This generally works well, however the slight problem I have with it is that something to do with the way I'm recursing the group means it is pulling back the users' display name, rather than their username (sAMAccountName) which is what I'm passing to the function in the first place. Is it possible to change how I'm referencing the group members to be able to look at their usernames rather than their display names? The code is below;

    public bool AddUserToGroup(string sUser, string sGroup)
        {
            PrincipalContext Context = new PrincipalContext(ContextType.Domain);
            UserPrincipal User = UserPrincipal.FindByIdentity(Context, sUser);
            GroupPrincipal Group = GroupPrincipal.FindByIdentity(Context, sGroup);
    
            Dictionary<string, int> GroupList = new Dictionary<string, int>();
    
            int Counter = 0;
    
            foreach (Principal Member in Group.GetMembers(true))
            {
                GroupList.Add(Member.Name, Counter);
                Counter = Counter + 1;
            }
    
            if (GroupList.ContainsKey(sDisplayName))
            {
    
                return false;
            }
            else
            {
                Group.Members.Add(User);
                Group.Save();
                return true;
            }
        }

    What I think you should be able to do is replace the line;

    if (GroupList.ContainsKey(sDisplayName))

    with;

    if (GroupList.ContainsKey(sUser))

    Sunday, January 12, 2014 7:01 PM

Answers

All replies