views:

209

answers:

1

Hi,

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.

+2  A: 

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
Could you please explain why I should use the keyword Using?
Haim Bender
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