简体   繁体   中英

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");
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM