Setting the Search Scope

To increase search performance, limit the search scope search to a single object or subset of objects. For this task, DirectorySearcher provides the SearchScope property.

The search scope can be set to one of the three following settings:

  • Base. This will search the bound object. For example, if you are bound to the domain, then it will search everything in that domain.
  • One level. This will search all objects contained in the same level as the bound object. For example, if you are bound to a group, it will search all groups or other objects that are at the same level as that group.
  • Subtree. This will search all objects contained in the subtree of the bound object. For example, if you are bound to a server, it will search all objects in the hiearchy that are under that server.

The following diagram illustrates how each of these scopes fits within your domain hierarchy. For more information, see Search Scope.

Domain search scopes.

The following code example shows how to use the SearchScope property to search a subtree.

[C#]

DirectoryEntry entry = new DirectoryEntry("LDAP://CN=users,DC=fabrikam,DC=com");
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.SearchScope = SearchScope.Subtree;
mySearcher.Filter = "(&(objectClass=user)(anr=test*))";
SearchResultCollection ResEnt = mySearcher.FindAll();
{
    // Handle results.
}
// Handle exceptions.