1
votes

I am try to write C# code for update Domain User Password in Server 2012. I'm using following code according to this Stack Overflow answer

using (var context = new PrincipalContext(ContextType.Domain, "test.com"))
{
    using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName))
    {
        user.SetPassword(newPassword);
        //user.ChangePassword(oldPassword, newPassword);
        user.Save();
    }
}

in getting following exception when running code

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --->
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

I also disabled password policy. Any advice?

1
Access is denied => the user the application is running on doesn't have enough privileges. - Camilo Terevinto

1 Answers

5
votes

The account your code is running under doesn't have permissions. You have two options:

  1. Run your program under credentials that do have the right permissions, or
  2. Use a different constructor for PrincipalContext and pass a username and password that has permissions to set the password:
var context = new PrincipalContext(ContextType.Domain, "test.com", "domain\username", "password");