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 PrincipalContext ctx = new PrincipalContext(ContextType.Domain); // define a "query-by-example" principal - here, we search for all users UserPrincipal qbeUser = new UserPrincipal(ctx); // 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
This code can be quite slow - especially if you have a large AD and a large number of users in your AD. But then again: is it really useful to list thousands of users in one folder? You may need to rethink your strategy there ....
Update: if you cannot use .NET 3.5, you will have to use the DirectorySearcher "legacy" class instead - something like this:
// find your default naming context DirectoryEntry deRoot = new DirectoryEntry("LDAP://RootDSE"); string defaultCtx = deRoot.Properties["defaultNamingContext"].Value.ToString(); // define a directory searcher for your default context string searchRootLDAPPath = "LDAP://" + defaultCtx; DirectoryEntry defaultDE = new DirectoryEntry(searchRootLDAPPath); // define searcher - search through entire subtree, search for users // (objectCategory=Person) DirectorySearcher dsAllUsers = new DirectorySearcher(defaultDE); dsAllUsers.SearchScope = SearchScope.Subtree; dsAllUsers.Filter = "(objectCategory=Person)"; // get the results SearchResultCollection result = dsAllUsers.FindAll(); // count the user objects found int count = result.Count;
As I mentioned, this will not work very well on a large AD, and you may encounter restrictions (for example, a maximum of 1,000 users) and other problems. Perhaps you should allow users to search for users, for example. by their name or something - instead of listing all your users (depending on the size of your AD).
source share