Существует два варианта изменения пароля пользователя. В одном случае мы действуем от имени самого пользователя, в другом случае от имени администратора.
Изменение пароля от имени администратора.
using System;
using System.Collections;
using System.DirectoryServices;
public class MyClass
{
public static void Main()
{
DirectoryEntry deUser = GetUser(strLogonName);
//Изменяем пароль при помощи метода AD "SetPassword"
deUser.Invoke("SetPassword", strNewPassword);
deUser.CommitChanges();
deUser.Close();
Console.ReadLine()
}
//Поиск пользователя по Logon Name
private static DirectoryEntry GetUser(string strLogonName)
{
DirectoryEntry rootDE = new DirectoryEntry("LDAP://domain", strAdminLogonName, strAdminPassword);
DirectorySearcher deSearch = new DirectorySearcher(rootDE);
deSearch.Filter = string.Format( "(&(objectClass=user)(samAccountName={0}))",strLogonName);
deSearch.SearchScope = SearchScope.Subtree;
SearchResult result = deSearch.FindOne();
rootDE.Close();
if(result !=null)
{
//Возвращаем DirectoryEntry полученную от имени администратора
return new DirectoryEntry(result.Path,string.Format("domain\\{0}",strAdminLogonName),strAdminPassword);
}
else
{
return null;
}
}
}
Изменение пароля от имени пользователя.
using System;
using System.Collections;
using System.DirectoryServices;
public class MyClass
{
public static void Main()
{
DirectoryEntry deUser = GetUser(strLogonName,strOldPassword);
//Изменяем пароль при помощи метода AD "ChangePassword", т.к. "SetPassword" доступен только администратору
deUser.Invoke("ChangePassword", new object[] {strOldPassword,strNewPassword});
deUser.CommitChanges();
deUser.Close();
Console.ReadLine()
}
//Поиск пользователя по Logon Name
private static DirectoryEntry GetUser(string strLogonName, string strPassword)
{
DirectoryEntry rootDE = new DirectoryEntry("LDAP://domain", strLogonName, strPassword);
DirectorySearcher deSearch = new DirectorySearcher(rootDE);
deSearch.Filter = string.Format( "(&(objectClass=user)(samAccountName={0}))",strLogonName);
deSearch.SearchScope = SearchScope.Subtree;
SearchResult result = deSearch.FindOne();
rootDE.Close();
if(result !=null)
{
//Возвращаем DirectoryEntry полученную от имени пользователя
return new DirectoryEntry(result.Path,string.Format("domain\\{0}",strLogonName),strPassword);
}
else
{
return null;
}
}
}