Search code examples
c#active-directoryou

Checking if a user exists in an ou


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.


Solution

  • 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 );        
             }
        }
    }