I\'m trying to figure out how to search AD from C# similarly to how \"Find Users, Contacts, and Groups\" works in the Active Directory Users and Computers tool. I have a str
You need to build the search string based on how you're looking for the user.
using (var adFolderObject = new DirectoryEntry())
{
using(var adSearcherObject = new DirectorySearcher(adFolderObject))
{
adSearcherObject.SearchScope = SearchScope.Subtree;
adSearcherObject.Filter = "(&(objectClass=person)(" + userType + "=" + userName + "))";
return adSearcherObject.FindOne();
}
}
userType should either be sAMAccountName or CN depending on how the username is formatted.
ex:
firstname.lastname (or flastname) will usually be the sAMAccountName
FirstName LastName will usually be the CN
System.DirectoryServices has two namespaces...DirectoryEntry and DirectorySearcher.
More info on the DirectorySearcher here:
http://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher.aspx
You can then use the Filter property to filter by Group, user etc...
So if you wanted to filter by account name you would set the .Filter to:
"(&(sAMAccountName=bsmith))"
and run the FilterAll method. This will return a SearchResultCollection that you can loop through and pull information about the user.