Share via


Remove the User Account from a Group

The user is removed from the specified group using the Remove method.

        internal static bool RemoveUserFromGroup(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
            {
                GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, group);
                UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, user);
                if (groupPrincipal != null && userPrincipal != null)
                {
                    
                    //Remove the user from the group
                    groupPrincipal.Members.Remove(userPrincipal);
                    groupPrincipal.Save();
                    bReturn = true;

                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Exception removing user from group. " + 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.