Last active
August 29, 2015 14:12
-
-
Save cpoDesign/fc61624cf9a09d186886 to your computer and use it in GitHub Desktop.
Example of changing password in AD (from: http://stackoverflow.com/questions/1066131/how-to-programaticly-change-active-directory-password)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using (var context = new PrincipalContext( ContextType.Domain )) | |
| { | |
| using (var user = UserPrincipal.FindByIdentity( context, IdentityType.SamAccountName, userName )) | |
| { | |
| user.SetPassword( "newpassword" ); | |
| // or | |
| user.ChangePassword( "oldPassword", "newpassword" ); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // alternative | |
| public void ChangeMyPassword(string domainName, string userName, string currentPassword, string newPassword) | |
| { | |
| try | |
| { | |
| string ldapPath = "LDAP://192.168.1.xx"; | |
| DirectoryEntry directionEntry = new DirectoryEntry(ldapPath, domainName + "\\" + userName, currentPassword); | |
| if (directionEntry != null) | |
| { | |
| DirectorySearcher search = new DirectorySearcher(directionEntry); | |
| search.Filter = "(SAMAccountName=" + userName + ")"; | |
| SearchResult result = search.FindOne(); | |
| if (result != null) | |
| { | |
| DirectoryEntry userEntry = result.GetDirectoryEntry(); | |
| if (userEntry != null) | |
| { | |
| userEntry.Invoke("ChangePassword", new object[] { currentPassword, newPassword }); | |
| userEntry.CommitChanges(); | |
| } | |
| } | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| throw ex; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment