Skip to content

Instantly share code, notes, and snippets.

@cpoDesign
Last active August 29, 2015 14:12
Show Gist options
  • Select an option

  • Save cpoDesign/fc61624cf9a09d186886 to your computer and use it in GitHub Desktop.

Select an option

Save cpoDesign/fc61624cf9a09d186886 to your computer and use it in GitHub Desktop.
using (var context = new PrincipalContext( ContextType.Domain ))
{
using (var user = UserPrincipal.FindByIdentity( context, IdentityType.SamAccountName, userName ))
{
user.SetPassword( "newpassword" );
// or
user.ChangePassword( "oldPassword", "newpassword" );
}
}
// 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