Can`t change AD password from c# code, throw exceptions

0

I have problem with c# script who change user AD password, when try change password, they throw exception

A constraint violation occurred. (Exception from HRESULT: 0x8007202F)

Code

DirectoryEntry entry = new DirectoryEntry("LDAP://domain.com", strLoginName, oldpassword.Text.ToString(), AuthenticationTypes.Secure);
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + strLoginName + ")";
search.SearchScope = SearchScope.Subtree;
search.CacheResults = false;

SearchResultCollection results = search.FindAll();
foreach (SearchResult result in results)
    entry = result.GetDirectoryEntry();

entry.Invoke("ChangePassword", new object[] { oldpassword.Text.ToString(), newpassword.Text.ToString() });
entry.CommitChanges();

Which could be a problem?

c#
.net
active-directory
ldap
asked on Stack Overflow Mar 28, 2012 by valch

1 Answer

3

Look here: https://stackoverflow.com/a/1066177/1027551

For your example it would look like this:

using (var context = new PrincipalContext(ContextType.Domain,"domain.com"))
using (var user = UserPrincipal.FindByIdentity( context, IdentityType.SamAccountName, 
                                                                 strLoginName )) 
{ 
  user.ChangePassword( oldPassword, newpassword ); 
} 

I hope that helps.

answered on Stack Overflow Mar 28, 2012 by Daro • edited Jan 16, 2018 by Liam

User contributions licensed under CC BY-SA 3.0