Search Users in Specific OU Active Directory

Muhammad Taqi picture Muhammad Taqi · Jan 7, 2015 · Viewed 12.9k times · Source

I have different OU in my Active Directory for different users, I want to get all users of a specific OU using C#.

Currently I have this filter, but it returns all users from all OU

(&(objectClass=User)(objectCategory=Person))

Kindly help me in finding users of specific user using ldap

Answer

marc_s picture marc_s · Jan 7, 2015

You can use a PrincipalSearcher and a "query-by-example" principal to do your searching:

// LDAP string to define your OU
string ou = "OU=Sales,DC=YourCompany,DC=com";

// set up a "PrincipalContext" for that OU
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "Yourcompany.com", ou))
{
    // define the "query-by-example" user (or group, or computer) for your search
    UserPrincipal qbeUser = new UserPrincipal(ctx);

    // set whatever attributes you want to limit your search for, e.g. Name, etc.
    qbeUser.Surname = "Smith";

    // define a searcher for that context and that query-by-example 
    using (PrincipalSearcher searcher = new PrincipalSearcher(qbeUser))
    {
        foreach (Principal p in searcher.FindAll())
        {
            // Convert the "generic" Principal to a UserPrincipal
            UserPrincipal user = p as UserPrincipal;

            if (user != null)
            {
                // do something with your found user....
            }
        }
    }

If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement. Or see the MSDN documentation on the System.DirectoryServices.AccountManagement namespace.

Of course, depending on your need, you might want to specify other properties on that "query-by-example" user principal you create:

  • DisplayName (typically: first name + space + last name)
  • SAM Account Name - your Windows/AD account name
  • User Principal Name - your "[email protected]" style name

You can specify any of the properties on the UserPrincipal and use those as "query-by-example" for your PrincipalSearcher.