7

I need to query current domain controller, probably primary to change user password.

(P)DC name should be fully qualified, i.e. DC=pdc,DC=example,DC=com (how to properly name such notation?)

How can it be done using C#?

4

4 回答 4

6

DomainController要在您的机器不属于的域中检索信息,您需要更多的东西。

  DirectoryContext domainContext =  new DirectoryContext(DirectoryContextType.Domain, "targetDomainName", "validUserInDomain", "validUserPassword");

  var domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext);
  var controller = domain.FindDomainController();
于 2012-11-13T14:44:40.213 回答
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;
}
于 2010-10-25T15:23:43.113 回答
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)));
}
于 2010-10-25T14:35:09.983 回答
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");
}
于 2010-10-25T14:36:29.900 回答