Tips : Querying Active Directory Objects using DirectorySearcher

Querying Active Directory objects using the DirectorySearcher can sometimes be challenging. For instance when you have more than 1000 objects in your directory and your FindAll query might fail to return you all the objects. The reason is by default the FindAll method returns only the first 1000 records.

The workaround here is to set the page size.

DirectorySearcher mySearcher = new DirectorySearcher(entry);

mySearcher.PageSize = 500;

Interesting point here is that you should set the page size that is less than 1000. If you set it more than 1000, it will take the server default settings which is 1000. Even though you set the page size as 500 the entire result set is retrieved. Apparently the search results are sliced up into page size of 500 and the entire result set is returned.

We also had a requirement to filter out the disabled users and the DirectorySearch filters can get really tricky. In this case the filter has to be constructed like this…

mySearcher.Filter = “(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))”;

This filter is going to pick all the “person” objects who are not disabled.

The search filter syntax looks a bit complicated, but basically it filters the search results to only include users – “objectCategory=person” and “objectClass=user” – and excludes disabled user accounts by performing a bitwise AND of the userAccountControl flags and the “account disabled” flag, and negating the results. Ref :


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: