Search code examples
c#active-directoryactive-directory-group

How do I apply a new group to a user in an OU in Microsoft Active Directory


My system has users login to register/renew their accounts. In the back end we already set a group and check if they are already there. We also changed our system and move users to a new OU if they are renewing (already in an OU).

What I want to do now is apply a new group to the user when they renew or register. Resulting in the user being a member of 2 groups.

DirectoryEntry instructorRoot = new DirectoryEntry(LDAP_OU_DIR); //root binding
instructorRoot.AuthenticationType = AuthenticationTypes.Signing | AuthenticationTypes.Secure | AuthenticationTypes.Sealing | AuthenticationTypes.FastBind;

DirectoryEntry instructor = new DirectoryEntry(LDAPRoot); //default value
instructor.AuthenticationType = instructorRoot.AuthenticationType;

/*Here is where im trying to look for the TestGroup group*/
DirectoryEntry instructorGroup = instructorRoot.Children.Find("CN="+TestGroup, "group");
instructorGroup.AuthenticationType = instructorRoot.AuthenticationType;

instructor = instructorRoot.Children.Add("CN=" + hfUser.Value, "user");
instructor.CommitChanges();

instructor.Properties["userPrincipalName"].Value = hfUser.Value + "@" + LDAPRoot;
instructor.Properties["sAMAccountName"].Value = hfUser.Value; //login name
instructor.CommitChanges();

/*Here is where im trying to add the InstTest group to the user*/ 
instructorGroup.Properties["member"].Add(instructor.Properties["distinguishedName"].Value); //add to instructors group
instructorGroup.CommitChanges(); //commit changes so that we can set primary group next
instructorGroup.Close();//close

instructor.Properties["PrimaryGroupID"].Value = 109929; //set primarygroup to instructors
instructor.CommitChanges();

Solution

  • private void AddMemberToGroup(string bindString, string newMember)
    {
        try
        {
            DirectoryEntry ent = new DirectoryEntry(bindString);
            ent.Properties["member"].Add(newMember);
            ent.CommitChanges();
        }
        catch (Exception e)
        {
            // do error catching stuff here
            return;
        }
    }
    

    Where bindString is the string that contains the full directory to the new group you want to add users to.

    AND

    newMember is the string obtained from the user object's .Properties["distinguishedName"].Value.ToString() method.