Home >Backend Development >C++ >How Can I Retrieve User Information (Name and Username) from Active Directory?
Retrieving User Information from Active Directory
To gather a list of users from Active Directory along with their corresponding usernames, first and last names, consider the following approach:
Understanding Active Directory Structure
Active Directory organizes data hierarchically, with containers and objects identified by distinguished names. Understanding this structure is crucial before performing queries.
LDAP Queries and PrincipalSearcher
Active Directory is a LDAP server, and LDAP queries can be utilized to retrieve information. For user-specific queries, the PrincipalSearcher class from System.DirectoryServices.AccountManagement is recommended.
Sample Code for Retrieval
The following code sample demonstrates how to retrieve user information using PrincipalSearcher:
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(); } } }
Attribute Considerations
Note that "givenName" corresponds to the First Name, while "sn" represents the Last Name. As for usernames, Active Directory stores two logon names: "samAccountName" (pre-Windows 2000) and "userPrincipalName" (post-Windows 2000).
The above is the detailed content of How Can I Retrieve User Information (Name and Username) from Active Directory?. For more information, please follow other related articles on the PHP Chinese website!