Home >Backend Development >C++ >How Can I Query and Retrieve Active Directory User Information Using .NET?

How Can I Query and Retrieve Active Directory User Information Using .NET?

Linda Hamilton
Linda HamiltonOriginal
2025-01-06 13:13:41584browse

How Can I Query and Retrieve Active Directory User Information Using .NET?

Working with Active Directory Users: A Beginner's Guide

As a beginner embarking on the realm of Active Directory, understanding the hierarchical structure of objects and the concept of distinguished names (CN) is crucial. Active Directory stores data in a similar manner to file systems, making it a hierarchical system.

Querying Users from Active Directory

To query users in Active Directory, you can employ several methods in .NET. One widely used option is PrincipalSearcher from System.DirectoryServices.AccountManagement. This approach is especially beneficial for searching specifically for user principal objects.

Example: Retrieving User Information

Consider the following code sample that demonstrates how to use PrincipalSearcher to retrieve user information, including username, first name, and last name:

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();

Additional Attributes

On Active Directory user objects, you'll encounter various attributes. Of particular note are:

  • givenName: Represents the First Name
  • sn: Represents the Last Name
  • samAccountName: Traditionally used user logon name
  • userPrincipalName: Post-Windows 2000 user logon name (typically)

The above is the detailed content of How Can I Query and Retrieve Active Directory User Information Using .NET?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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