Create user Active Directory: Exception has been thrown by the target of an invocation. thrown at UserPrincipal


When I try to create user in active directory I get an exception:

(Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) error


UserPrincipal userPrincipal = new UserPrincipal(principalContext);
userPrincipal.SamAccountName = serviceAccount.SAMAccountName;
userPrincipal.PasswordNeverExpires = serviceAccount.PasswordNeverExpires;
userPrincipal.Enabled = serviceAccount.Enabled;

// Creates the account
catch (Exception e)
    return false;
return true;

I get the error at

asked on Stack Overflow Jul 29, 2019 by saurav7044 • edited Jul 29, 2019 by marc_s

1 Answer


E_ACCESSDENIED means that the account you are using to do this does not have permissions to do what you're doing.

You don't show your code where you create your PrincipalContext object, but if you did not give it a username and password, then it is using whatever credentials the process is running under, which sounds like it's not good enough.

You need to use one of the PrincipalContext constructors that lets you provide a username and password. For example:

var principalContext = new PrincipalContext(

Where "" is your domain name, ""ou=Users,dc=example,dc=com"" is the OU where you want to create the accounts, and "username" and "password" belong to an account that has permissions to create user accounts in that OU.

answered on Stack Overflow Jul 29, 2019 by Gabriel Luci

User contributions licensed under CC BY-SA 3.0