LDAP: How to add a new user to a group inside an OU

10,397

Basically, to add a user to an existing group, you need to bind to that group and update it's member property, using the user's fully qualified distinguished name:

DirectoryEntry deGroup = new DirectoryEntry("LDAP://CN=Internal,OU=Sharepoint_Groups,DC=Company,DC=local");

string userDN = newUser.Properties["distinguishedName"][0].ToString();

deGroup.Properties["member"].Add(userDN);
deGroup.CommitChanges();

A great resource for stuff like this is the CodeProject article How to do just about everything in Active Directory using C# - lots of useful code samples!

Share:
10,397
Christian P.
Author by

Christian P.

Updated on July 25, 2022

Comments

  • Christian P.
    Christian P. almost 2 years

    I have some code using DirectoryEntry to manipulate the local Active Directory via LDAP. Currently I find a specific OU, add a user to it, update the properties of the user and then commit all changes:

    DirectoryEntry ldapRoot = new DirectoryEntry(ldapString, user, password);
    DirectoryEntry userGroup = ldapRoot.Children.Find("OU=OUGroup");
    DirectoryEntry newUser = userGroup.Children.Add("CN=" + userName, "user");
    newUser.Properties["displayName"].Value = displayName;
    
    ...
    
    newUser.CommitChanges();
    userGroup.Close();
    ldapRoot.Close();
    

    ldapString is something akin to LDAP:\\DC=company,DC=local, basically it's just fetching the root entry.

    I change several Properties, but it's all working fine. However, I have another OU called SharePoint_Groups, which has a group inside called Internal. I want to add the new user as a member of this group, but I'm at a loss of how to do it. I tried the following:

    DirectoryEntry spGroup = ldapRoot.Children.Find("OU=Sharepoint_Groups");
    DirectoryEntry internal = spGroup.Children.Find("CN=Internal");
    

    It does not work and I am not sure how I should address Internal - is CN= correct or should I use some other specification?

    And, once I have the correct group, how do I add the existing user to it?

    Thanks in advance