Home > Backend Development > C++ > How Can I Retrieve User Information from Active Directory Using PrincipalSearcher?

How Can I Retrieve User Information from Active Directory Using PrincipalSearcher?

Linda Hamilton
Release: 2025-01-06 13:30:41
Original
865 people have browsed it

How Can I Retrieve User Information from Active Directory Using PrincipalSearcher?

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:

  • givenName: First Name
  • sn: Last Name
  • samAccountName: Pre-Windows 2000 user logon name
  • userPrincipalName: Logon name used after Windows 2000

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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template