dev
dev

Reputation: 71

c# finding active directory user by sAMAccount

Newbie to .Net 4.0.
We have a script that currently resets a user password with the following code:

 DirectoryEntry de = new DirectoryEntry("myLdapString");

 DirectoryEntry ChgPwd = de.Children.Find("CN=" + "myuserid", "user");

 ChgPwd.Invoke("SetPassword", new object[] { "newPWD" });

 ChgPwd.CommitChanges();

I want to change this so that I am pointing to the user using "sAMAccount=" rather than "CN=". But changing that in my Find string above does not work. Can someone help with the proper syntax for this change? Thanks

Upvotes: 0

Views: 246

Answers (1)

user553838
user553838

Reputation: 217

you can use System.DirectoryServices.AccountManagement Namespace to manage acitve directory account.

code like

using(PrincipalContext principalContext = new PrincipalContext( ContextType.Domain,
            TargetDomain,
            TargetDomainUserName,
            TargetDomainPassword))
 using(var userPrincipal = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, "somaloginname"))
{ 
userPrincipal.SetPassword(newPassword);
//or userPrincipal.ChangePassword
            userPrincipal.Save();
            }

MSDN:UserPrincipal Class

Upvotes: 3

Related Questions