Last time I wrote about how you can reach the Active Directory search dialog in Windows 7. Today I’ll show you how to search comfortable for users in the Active Directory by using C#. The emphasis is on comfort, because there are quite a few articles on the subject in general, on the internet.
However, most of the shown methods/solutions are build exclusively around System.DirectoryServices.ActiveDirectory and the DirectorySearcher. But ever since .NET 3.5 it is also possible to search in the Active Directory much easier.
But let us come to the point. In the following example, I mostly use methods from the System.DirectoryServices.AccountManagement namespace. And here’s how:
//Create a shortcut to the appropriate Windows domain PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "myDomain"); //Create a "user object" in the context UserPrincipal user = new UserPrincipal(domainContext); //Specify the search parameters user.Name = "he*"; //Create the searcher //pass (our) user object PrincipalSearcher pS = new PrincipalSearcher(); pS.QueryFilter = user; //Perform the search PrincipalSearchResult<Principal> results = pS.FindAll(); //If necessary, request more details Principal pc = results.ToList(); DirectoryEntry de = (DirectoryEntry)pc.GetUnderlyingObject(); //Output first result of the test MessageBox.Show(de.Properties["mail"].Value.ToString());
After you’ve now seen the source code, there are of course a few more notes to it. In line 9, I set the Name property of user. The * is seen as a wildcard. It would be in line 17 all Active Directory user entries returned whose name starts with “he”.
Basically, it has to be said, that you can search for many other properties, instead of the Name property set, which then act as filters. Also, the combining of a plurality of properties is possible.
Also, I would like to mention, that from line 21 on, all code is optional. In most cases, the principal objects contain all the data you need to know. However, these principal objects do not contain all properties that can be set as in the Active Directory.
Should you are searching an actual shaft that does not grasp the principal object, so you have to fall back on the old way method, raised at the beginning of this article.