如何通过c#代码将密码更改为用户帐户?

如何通过c#代码将密码更改为用户帐户?

使用活动目录:

// 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); } 

您可以在此处更改本地用户帐户中的示例:

http://msdn.microsoft.com/en-us/library/ms817839

其他替代方案可能是使用互操作性并调用非托管代码: netapi32.dll

http://msdn.microsoft.com/en-us/library/aa370650(VS.85).aspx

这是一种更简单的方法,但是您需要从.Net 4.0引用System.DirectoryServices.AccountManagement。

 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); } } } } 
  DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntry grp; grp = AD.Children.Find("test", "user"); if (grp != null) { grp.Invoke("SetPassword", new object[] { "test" }); } grp.CommitChanges(); MessageBox.Show("Account Change password Successfully"); 

“在管理员中运行以更改所有用户

这适用于AD和本地帐户。

如果要通过C#调用此API,可以使用此签名将API NetUserChangePassword导入C#代码:

 [DllImport("netapi32.dll", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall,SetLastError=true )] static extern uint NetUserChangePassword ( [MarshalAs(UnmanagedType.LPWStr)] string domainname, [MarshalAs(UnmanagedType.LPWStr)] string username, [MarshalAs(UnmanagedType.LPWStr)] string oldpassword, [MarshalAs(UnmanagedType.LPWStr)] string newpassword);