DevBassem
DevBassem

Reputation: 33

C# add active directory user to group

I'm trying to create a user and add it to 3 groups, the creation is working properly but adding user to groups sometimes it's working and sometimes show this error:

there is no such object on the server

my code for adding user to group :

try
            {
                DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + group, ADUsername, ADPassword);
                if (dirEntry != null)
                {
                    dirEntry.Properties["member"].Add(userPrincipal.DistinguishedName);
                    dirEntry.CommitChanges();
                    dirEntry.Close();
                }
            }
            catch (System.DirectoryServices.DirectoryServicesCOMException E)
            {
                //doSomething with E.Message.ToString();

            }

Upvotes: 2

Views: 2943

Answers (1)

Jono
Jono

Reputation: 59

I have experienced this and in my situation it was because the newly created object hadn’t replicated to all of our DCs. I resolved this by introducing a 3 second delay after I created the user. I then proceeded with adding the user to the groups.

Upvotes: 2

Related Questions