Retrieving User Information from Active Directory Using PrincipalSearcher
If you're new to Active Directory, it's crucial to understand its hierarchical data structure and LDAP querying capabilities. To retrieve a list of users, the PrincipalSearcher class in System.DirectoryServices.AccountManagement provides an intuitive approach.
using (var context = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
establishes a connection to the specified domain.
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
creates a searcher object for finding user principals.
Within the FindAll() loop, the DirectoryEntry object associated with each result is obtained to access properties such as:
The code snippet below provides an example of this approach:
using (var context = new PrincipalContext(ContextType.Domain, "yourdomain.com")) { using (var searcher = new PrincipalSearcher(new UserPrincipal(context))) { foreach (var result in searcher.FindAll()) { DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry; Console.WriteLine("First Name: " + de.Properties["givenName"].Value); Console.WriteLine("Last Name : " + de.Properties["sn"].Value); Console.WriteLine("SAM account name : " + de.Properties["samAccountName"].Value); Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value); Console.WriteLine(); } } } Console.ReadLine();
This solution efficiently retrieves the desired user information from Active Directory.
The above is the detailed content of How Can I Retrieve User Information from Active Directory Using PrincipalSearcher?. For more information, please follow other related articles on the PHP Chinese website!