好吧,我为解决上述问题所做的工作如下:
- 设置一个可以查询两个 AD 的服务帐户
第一种方法
private bool ResetDomainAccountPassword(string loginName, string oldPassword, string newPassword)
{
DirectoryEntry e2 = new DirectoryEntry();
try
{
// ----- Get the credentials for the active directory service account.
string userName = ServiceUser();
string password = ServicePassword();
using (DirectoryEntry e = new DirectoryEntry(Path(), userName, password, AuthenticationTypes.Secure))
{
string search = string.Format("(sAMAccountName={0})", loginName);
DirectorySearcher s = new DirectorySearcher(e, search);
SearchResult sr = s.FindOne();
if (sr != null)
{
e2 = sr.GetDirectoryEntry();
e2.Username = userName;
e2.Password = password;
}
if (e2.NativeGuid != null)
{
return ResetPassword(e2, oldPassword, newPassword);
}
else
return false;
}
}
catch (Exception ex)
{
Exception inner = ex.InnerException;
// ----- Handle exception here.
return false;
}
finally
{
e2.Dispose();
}
}
重置密码方法
private bool ResetPassword(DirectoryEntry e, string oldPassword, string newPassword)
{
try
{
ActiveDs.IADsUser u = e.NativeObject as ActiveDs.IADsUser;
Type t = e.NativeObject.GetType();
if (u.IsAccountLocked)
{
u.IsAccountLocked = false;
u.SetInfo();
}
u.SetPassword(newPassword);
u.SetInfo();
e.CommitChanges();
return true;
}
catch (Exception ex)
{
Exception inner = ex.InnerException;
// ----- Handle exception here.
return false;
}
}
我忘记了一件事:您需要添加对“Active DS 类型库”(COM)的引用。