以编程方式确定当前域控制器

我需要查询当前的域控制器,可能是主要的更改用户密码。

(P)DC名称应该是完全合格的,即DC=pdc,DC=example,DC=com (如何正确命名这种表示法?)

如何使用C#完成?

要在DomainController存在于您的计算机所属的域中时检索信息,您还需要更多信息。

  DirectoryContext domainContext = new DirectoryContext(DirectoryContextType.Domain, "targetDomainName", "validUserInDomain", "validUserPassword"); var domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext); var controller = domain.FindDomainController(); 

我们在内部应用程序中使用这样的东西。

应该返回类似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; } 

(需要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 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))); } 

如果您希望与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"); }