Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to get only users from DirectorySearcher query

Status
Not open for further replies.

mrgulic

Technical User
Sep 18, 2001
248
US
I have the following code that i use to search for users in the domain. When I enter a complte user name it finds it but when i use wildcards and gets even computer names that contain the string too.

How to i filter for only only users? There has to be some flag that indicates a AD objct is a user, computer, etc. I thought that what the following did "objectClass=user".

Code:
public SearchResultCollection GetDirectoryUsers(string user)
{
	try
	{
		DirectorySearcher searchADS = new DirectorySearcher("LDAP://mydomain.com/CN=Users,DC=mydomain,DC=com");
		searchADS.Filter = "(&(objectClass=user)(SAMAccountName=" + user + "))";
		searchADS.SearchScope = SearchScope.Subtree;
		searchADS.PropertiesToLoad.Add("cn");
		SearchResultCollection resultsAll = searchADS.FindAll();
		return resultsAll;
	}
	catch (Exception)
	{
		return null;
	}
}
 
Of course after several days of searching for an answer, a few hours after posting something here and a small change in the seach string on google yeilds positive results.


I needed the following added to my filter ("objectCategory=Person")

So i changed this:
Code:
searchADS.Filter = "(&(objectClass=user)(SAMAccountName=" + user + "))";
to this:
Code:
searchADS.Filter = "(&(objectCategory=Person)(objectClass=user)(SAMAccountName=" + user + "))";
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top