Reputation: 1612
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?
Upvotes: 1
Views: 5029
Reputation: 40858
The account your code is running under doesn't have permissions. You have two options:
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");
Upvotes: 5