how to change password to user account, by c# code?
Here is a simpler way to do this, however you will need to reference System.DirectoryServices.AccountManagement from .Net 4.0
namespace PasswordChanger
{
using System;
using System.DirectoryServices.AccountManagement;
class Program
{
static void Main(string[] args)
{
ChangePassword("domain", "user", "oldpassword", "newpassword");
}
public static void ChangePassword(string domain, string userName, string oldPassword, string newPassword)
{
try
{
using (var context = new PrincipalContext(ContextType.Domain, domain))
using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName))
{
user.ChangePassword(oldPassword, newPassword);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
Using active directory:
// Connect to Active Directory and get the DirectoryEntry object.
// Note, ADPath is an Active Directory path pointing to a user. You would have created this
// path by calling a GetUser() function, which searches AD for the specified user
// and returns its DirectoryEntry object or path. See http://www.primaryobjects.com/CMS/Article61.aspx
DirectoryEntry oDE;
oDE = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);
try
{
// Change the password.
oDE.Invoke("ChangePassword", new object[]{strOldPassword, strNewPassword});
}
catch (Exception excep)
{
Debug.WriteLine("Error changing password. Reason: " + excep.Message);
}
Here you have example to change it in the local user account:
http://msdn.microsoft.com/en-us/library/ms817839
Other alternative could be using interoperability and call unmanaged code: netapi32.dll
http://msdn.microsoft.com/en-us/library/aa370650(VS.85).aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With