If you are using .NET 3.5 or later, you can use PrincipalSearcher and "query by example" to perform a search:
// create your domain context and define what container to search in - here OU=Employees PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "OU=Employees,DC=YourCompany,DC=com"); // define a "query-by-example" principal - here, we search for a UserPrincipal // that is still active UserPrincipal qbeUser = new UserPrincipal(ctx); qbeUser.Enabled = true; // create your principal searcher passing in the QBE principal PrincipalSearcher srch = new PrincipalSearcher(qbeUser); // find all matches foreach(var found in srch.FindAll()) { // do whatever here - "found" is of type "Principal" - it could be user, group, computer..... }
If you havenβt already done so, absolutely read the MSDN article "Security Principles in the .NET Framework 3.5" , which shows how to make better use of the new features in System.DirectoryServices.AccountManagement
If you prefer the "old" style of .NET 2.0, you need to create a DirectoryEntry base that matches your organizational unit that you want to list, and then you need to create a DirectorySearcher that looks for objects - something like this:
// create your "base" - the OU "FormerEmployees" DirectoryEntry formerEmployeeOU = new DirectoryEntry("LDAP://OU=FormerEmployees,DC=YourCompany,DC=com"); // create a searcher to find objects inside this container DirectorySearcher feSearcher = new DirectorySearcher(formerEmployeeOU); // define a standard LDAP filter for what you search for - here "users" feSearcher.Filter = "(objectCategory=user)"; // define the properties you want to have returned by the searcher feSearcher.PropertiesToLoad.Add("distinguishedName"); feSearcher.PropertiesToLoad.Add("sn"); feSearcher.PropertiesToLoad.Add("givenName"); feSearcher.PropertiesToLoad.Add("mail"); // search and iterate over results foreach (SearchResult sr in feSearcher.FindAll()) { // for each property, you need to check where it present in sr.Properties if (sr.Properties["description"] != null && sr.Properties["description"].Count > 0) { string description = sr.Properties["description"][0].ToString(); } }
source share