Retrieve User Data from Active Directory
Introduction:
Accessing user information from Active Directory (AD) is an essential task in many IT environments. This guide provides a comprehensive solution for obtaining a list of users, including their usernames, first names, and last names.
Background on Active Directory:
Active Directory is an LDAP (Lightweight Directory Access Protocol) server that organizes objects hierarchically, similar to a file system. Each object has a distinguished name (DN) that uniquely identifies it in the directory.
Querying Active Directory using LDAP:
There are several methods for querying AD in .NET. One convenient option is to use PrincipalSearcher from the System.DirectoryServices.AccountManagement namespace.
Example Query:
The following code demonstrates a query that retrieves the necessary user information:
using System.DirectoryServices.AccountManagement; PrincipalContext context = new PrincipalContext(ContextType.Domain, "yourdomain.com"); PrincipalSearcher 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(); }
Explanation:
The above is the detailed content of How Can I Retrieve User Data (Username, First Name, Last Name) from Active Directory Using C#?. For more information, please follow other related articles on the PHP Chinese website!