Question

I'm trying to add a user, add them to a group, and then make that group the primary group for the user. I've been using System.DirectoryServices.AccountManagement for all the AD access. I've added the user using:

principalContext = new PrincipalContext(ContextType.Domain, Globs.strDomain, userOU);
UserPrincipal userPrincipal = new UserPrincipal(principalContext);
userPrincipal.Surname = this.textBox_LastName.Text;
userPrincipal.GivenName = this.textBox_FirstName.Text;
userPrincipal.SamAccountName = this.textBox_LogonName.Text;
userPrincipal.MiddleName = this.textBox_Initials.Text;
userPrincipal.DisplayName = label_DisplayName.Text;
userPrincipal.Description = this.comboBox_Description.Text;
userPrincipal.UserPrincipalName = this.textBox_LogonName.Text;
userPrincipal.SetPassword(defaultPassword);
userPrincipal.PasswordNeverExpires = true;
userPrincipal.Enabled = true;
userPrincipal.Save();

I then add the user to a group using:

using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Globs.strDomain))
{
    GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName);
    group.Members.Add(pc, IdentityType.UserPrincipalName, userId);
    group.Save();
}

Is there a quick way to take that group and make it the primary group for the user? Once I have made the primary group I will remove the default group of "Domain Users". Any help is appreciated. -Cary

Was it helpful?

Solution

That is controlled by the attribute primaryGroupID. It is not exposed by the default UserPrincipal so you must either make your own subclass that exposes it or use the more RAW underlying System.DirectoryServices objects and set the attribute.

(UPDATE: 2008 and earlier articles of MSDN magazine are no longer available via a web interface. You need to download the January 2008 magazine's chm file and find the article "Look it Up: Managing Directory Security Principals in the .NET Framework 3.5" to see the article about making a subclass)

The attribute value is the RID of the group so you need to get the primaryGroupToken attribute from the new group and set it to the users primaryGroupID attribute.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top