我需要查询当前的域控制器,可能是主要的更改用户密码。
(P)DC名称应该是完全合格的,即DC=pdc,DC=example,DC=com
(如何恰当地命名这种表示法?)
如何使用C#完成?
答案 0 :(得分:5)
要在您的机器所属的域中存在DomainController
时检索信息,您需要更多内容。
DirectoryContext domainContext = new DirectoryContext(DirectoryContextType.Domain, "targetDomainName", "validUserInDomain", "validUserPassword");
var domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext);
var controller = domain.FindDomainController();
答案 1 :(得分:2)
(需要System.DirectoryServices.AccountManagement.dll):
using (var context = new System.DirectoryServices.AccountManagement.PrincipalContext(ContextType.Domain))
{
string server = context.ConnectedServer; // "pdc.examle.com"
string[] splitted = server.Split('.'); // { "pdc", "example", "com" }
IEnumerable<string> formatted = splitted.Select(s => String.Format("DC={0}", s));// { "DC=pdc", "DC=example", "DC=com" }
string joined = String.Join(",", formatted); // "DC=pdc,DC=example,DC=com"
// or just in one string
string pdc = String.Join(",", context.ConnectedServer.Split('.').Select(s => String.Format("DC={0}", s)));
}
答案 2 :(得分:2)
我们正在为我们的内部应用程序使用这样的东西。
应返回DC=d,DC=r,DC=ABC,DC=com
public static string RetrieveRootDseDefaultNamingContext()
{
String RootDsePath = "LDAP://RootDSE";
const string DefaultNamingContextPropertyName = "defaultNamingContext";
DirectoryEntry rootDse = new DirectoryEntry(RootDsePath)
{
AuthenticationType = AuthenticationTypes.Secure;
};
object propertyValue = rootDse.Properties[DefaultNamingContextPropertyName].Value;
return propertyValue != null ? propertyValue.ToString() : null;
}
答案 3 :(得分:0)
如果您希望与Active Directory进行交互,则不必知道FSMO角色的大部分位置。如果要从程序中更改AD拓扑(我不愿意),请查看DomainController类。
如果要更改用户密码,可以在User对象上调用这些操作,Active Directory将确保正确复制更改。
从http://www.rootsilver.com/2007/08/how-to-change-a-user-password
复制public static void ChangePassword(string userName, string oldPassword, string newPassword)
{
string path = "LDAP://CN=" + userName + ",CN=Users,DC=demo,DC=domain,DC=com";
//Instantiate a new DirectoryEntry using an administrator uid/pwd
//In real life, you'd store the admin uid/pwd elsewhere
DirectoryEntry directoryEntry = new DirectoryEntry(path, "administrator", "password");
try
{
directoryEntry.Invoke("ChangePassword", new object[]{oldPassword, newPassword});
}
catch (Exception ex) //TODO: catch a specific exception ! :)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("success");
}