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?
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
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With