/// <summary> /// Makes user with given login name member of group with given name if exists. /// </summary> /// <param name="groupName">group name</param> public void AssignUserGroup(string loginName, string groupName) { // Find user entry by login name UserPrincipal userEntry = UserPrincipal.FindByIdentity(activeDirectoryDomain, IdentityType.SamAccountName, loginName); // Search for group with matching name PrincipalSearchResult <Principal> activeDirectoryGroups = this.ListGroupsByName( this.activeDirectoryDomain, groupName); if (activeDirectoryGroups.Count <Principal>() != 0) { GroupPrincipal group = (GroupPrincipal)activeDirectoryGroups.First <Principal>(); // make user member of group group.Members.Add(userEntry); // save changes group.Save(); group.Dispose(); } else { // throw exception to notify the group does not exists throw new ApplicationException("Domain group not found."); } // dispose the objects userEntry.Dispose(); activeDirectoryGroups.Dispose(); }