如何通过c#代码将密码更改为用户帐户?
答
使用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);
}
在这里你有例子来改变它在本地用户帐户:
http://msdn.microsoft.com/en-us/library/ms817839
其它替代可使用互操作和调用非托管代码:netapi32.dll
http://msdn.microsoft.com/en-us/library/aa370650(VS.85).aspx
答
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");
“运行管理员更改所有用户
答
这里有一个简单的方法来做到这一点,但是你需要从.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);
}
}
}
}
哪个用户参考System.DirectoryServices.AccountManagement帐户?域?任何应用?系统? – 2010-11-23 08:02:15
哪个用户帐户?????? – TalentTuner 2010-11-23 08:05:18
可能是这个问题的愚蠢(取决于你想改变什么密码):http://stackoverflow.com/questions/234845/change-local-administrator-password-in-c – 2010-11-23 08:06:06