Search code examples
c#active-directoryuserprincipal

UserPrincipal doesn't let me add new user


I'm having a bit of a problem when trying to add a new user or trying to access an already existing user in the Active Directory through my C# program.

    var principalContext = new PrincipalContext(ContextType.Domain, "domain", "OU=Users,OU=SI");
    UserPrincipal usr = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, samAccountStr);

It's throwing the "An operations error ocurred" exception. I found out that it's supposed to that if the user doesn't have the right permission for the Active Directory but I am running the program as administrator with the account of someone who can add users to the AD. So I really don't know what could be wrong. When I try to add a new user I try it like this:

    var principalContext = new PrincipalContext(ContextType.Domain, "domain", "OU=Users,OU=SI");
    UserPrincipal usr = new UserPrincipal(principalContext);

The code for the existing user already breaks when I call FindByIdentity. The code for the new user however breaks after I try to set some values for the new user principle. For example:

    usr.Surname = sn;

The extended error says it's: SvcErr: DSID-031007DF, problem 5012 (DIR_ERROR)

So any idea as to what might be causing it if it's not a permission problem?


Solution

  • You have to provide a full Distinguished Name for the OU, including the domain. This is not valid:

    "OU=Users,OU=SI"
    

    Something like this would be (if your domain was "domain.com"):

    "OU=Users,OU=SI,DC=domain,DC=com"