1

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?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Ishara Madawa
  • 1,502
  • 2
  • 14
  • 27

1 Answers1

5

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");
Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84