Determine current domain controller programmatically

前端 未结 4 1639
后悔当初
后悔当初 2020-12-18 02:20

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

4条回答
  •  不知归路
    2020-12-18 03:00

    If you are looking to interact the Active Directory, you shouldn't have to know where the FSMO roles are for the most part. If you want to change the AD topology from your program (I wouldn't), look at the DomainController class.

    If you want to change a user password, you can invoke those actions on the User object, and Active Directory will make sure that the changes are properly replicated.

    copied from 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");
    }
    

提交回复
热议问题