Add the User Account to a Group

The application searches for the newly persisted employee, and then searches for groups to which the employees needs to be added using the FindByIdentity method. After the group is retrieved, the user principal is added to the group.

        internal static bool AddUserToGroup(string user, string group)
        {
            // Creating the PrincipalContext
            PrincipalContext principalContext = null;
            try
            {
                principalContext = new PrincipalContext(ContextType.Domain, "fabrikam", "DC=fabrikam,DC=com");
            }
            catch (Exception e)
            {
                MessageBox.Show("Failed to create PrincipalContext. Exception: " + e);
                Application.Exit();
            }


            bool bReturn = false;
            try
            {
                UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, user);
                GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, group);

                if (groupPrincipal != null)
                {
                    //check if user is already a member
                    if (groupPrincipal.Members.Contains(principalContext, IdentityType.SamAccountName, user))
                    {
                        MessageBox.Show(group + " already contains " + user);
                        return false;
                    }
                    
                    //Adding the user to the group
                    groupPrincipal.Members.Add(userPrincipal);
                    groupPrincipal.Save();
                    bReturn = true;
                }
                else
                    MessageBox.Show("Could not find the group [" + group + "]");


            }
            catch (Exception e)
            {
                MessageBox.Show("Exception adding user to Groups. " + e);                
            }            
                
            return bReturn;
        }

See Also

Reference

System.DirectoryServices.AccountManagement

Concepts

About System.DirectoryServices.AccountManagement
Using System.DirectoryServices.AccountManagement

Send comments about this topic to Microsoft.

Copyright © 2008 by Microsoft Corporation. All rights reserved.