Muhammad Taqi
Muhammad Taqi

Reputation: 53

Search Users in Specific OU Active Directory

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

Upvotes: 4

Views: 16401

Answers (2)

rjzii
rjzii

Reputation: 14563

One option is to just set the organization unit (OU) when you create your DirectoryEntry object:

using (var entry = new DirectoryEntry($"LDAP://OU={unit},OU=Accounts,DC={domain},DC=local"))
{
    // Setup your search within the directory
    var search = new DirectorySearcher(entry)
    {
        Filter = "(&(objectCategory=person)(objectClass=user)(memberOf=*))"
    };

    // Set the properties to be returned
    search.PropertiesToLoad.Add("SamAccountName");

    // Get the results
    var results = search.FindAll();

    // TODO Process the results as needed...
}

Upvotes: 4

marc_s
marc_s

Reputation: 755321

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.

Upvotes: 7

Related Questions