Armin
Armin

Reputation: 21

C# Add LDAP user to group

I am writing the following method to add users on active directory to a custom group in C#. I have an OU named "SHO Users" and a sub-ou named "SHO Sharepoint User" All my users are saved under sub-ou. I do have a group under the first ou "SHO Users" named "Test GRP". I need to add some of the users to "Test GRP" group with the following code but no luck. I'll really appreciate for any help. Thanks

public void AddToGroup(string userDn, string groupDn)
{
    try
    {
        DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + groupDn);
        dirEntry.Properties["member"].Add(userDn);
        dirEntry.CommitChanges();
        dirEntry.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //doSomething with E.Message.ToString();

    }
}

protected void btnAdd_Click(object sender, EventArgs e)
{
string UserId = txtFirstname.Text + " " + txtLastname.Text;
AddToGroup("CN=" + UserId + ",OU=SHO Sharepoint User,OU=SHO Users,dc=test,dc=com", "CN=Test GRP,CN=Groups,DC=test,DC=com");
}

Upvotes: 2

Views: 6879

Answers (1)

alu
alu

Reputation: 759

Try this function:

public void AddToGroup(string userDn, string groupDn)
{
    try
    {
        DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + groupDn);
        dirEntry.Invoke("Add", new object[] { userDn });
        dirEntry.CommitChanges();
        dirEntry.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //doSomething with E.Message.ToString();

    }
}

To check if the connection string is right you can use the tool AdExplorer. Just select the object you are interested in and copy the address from the top bar.

Upvotes: 1

Related Questions