Question

I'm trying to create a new UserPrincipal in a specific OU inside ActiveDirectory, and it returns an Exception with the message 'Object already exists'. (obviously) The user don't exists in that OU, and I'm testing its existence.

What am I doing wrong?

Here's the code throwing the exception:

public UserPrincipal CreateUser(string username, string pass,
        string givenName, string surname) {
    PrincipalContext context = this.principalContext;
    UserPrincipal user = new UserPrincipal(context);
    user.SamAccountName = username;
    user.UserPrincipalName = username;
    user.GivenName = givenName;
    user.Surname = surname;
    user.SetPassword(pass);
    user.Save();
    return user;
}

Edit 1: After unit tests, I found that the code is ok. I use this method in a lib (where I run the tests), that is called by another application, which has an Windows authentication mode enabled. Maybe the app is sending that authentication to AD?

Was it helpful?

Solution 2

sAMAccountName must be unique across the enterprise. You mention 'specific OU' when creating the user. Is it possible you have another user with the same username/sAMAccountName in a different OU?

OTHER TIPS

I experienced the same error but didn't help much from the accepted answer above as in my case the issue is not due to sAMAccountName but due to Name. The account attempted to create had unique sAMAccountName but the name already exists which resulted in this error.

The object already exists.

Looks like the error can happen against more than one Active Directory account properties

  • sAMAccountName
  • Name

Recommendation:
Like in most of the cases, it is better to check for existence before creating a new entry.

Useful links:

I hope this helps someone.

Cheers,

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