1

I want check if a selected user exists within an OU (by the username he/she logs on to), what the rightest way to get this done? After that I want to select the user and change his/her password.

I found some help here: http://www.codeproject.com/KB/system/everythingInAD.aspx#46

But the code I found looked like this:

public static bool Exists(string objectPath)
{
    bool found = false;
    if (DirectoryEntry.Exists("LDAP://" + objectPath))
    {
        found = true;
    }
    return found;
}

wich could be summeried as:

return DirectoryEntry.Exists("LDAP://" + objectPath);

So I don't really know who to trust here, and what I should pass as objectPath if all I have is a username and OU name and a domain name.

Please help.

Thanks.

Haim Bender
  • 7,937
  • 10
  • 53
  • 55

1 Answers1

4

Since user name need to be unique within a domain, I don't think I'd be overly concerned with the OU. Building this in could make your code more fragile and will make it more complicated. I would try using the new UserPrincipal class if you can.

using (var context = new PrincipalContext( ContextType.Domain ))
{
     using (var user = UserPrincipal.FindByIdentity( context, IdentityType.SamAccountName, userName ))
     {
         if (user != null)
         {
             user.ChangePassword( oldPassword, newPassword );
             // or if you don't have the user's old password and
             // do have enough privileges.
             // user.SetPassword( newPassword );        
         }
    }
}
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • Could you please explain why I should use the keyword Using? – Haim Bender Dec 27 '09 at 14:10
  • 1
    PrincipalContext and UserPrincipal both implement IDisposable. By wrapping them in a using statement, you make sure that Dispose is called on the object when you are finished with it and the unmanaged resources used by the objects are released. – tvanfosson Dec 27 '09 at 16:01