Thursday, 17 April 2014

C#: Retrieve user data from Active Directory

The code snippet below shows how to retrieve user information from ActiveDirectory using the PrincipalSearcher class:
var context = new PrincipalContext(ContextType.Domain, "");
var user = new UserPrincipal(context);

// search by alias
user.SamAccountName = "useralias";

// You can also search by other properties e.g. Display Name
//user.DisplayName = "John Doe";

// perform the search 
var search = new PrincipalSearcher(user);
user = (UserPrincipal)search.FindOne();

if (user != null) {
} else {
   Console.WriteLine("No user found");

Searching across multiple domains

The code above will search for users in the specified domain only. However, you will often want to search across multiple domains. In that case you will need to provide the parent domain name together with appropriate port. Let's say you have a hierarchy like this:
  - ...
To search across all children of the domain construct your PrincipalContext like this:
var context = new PrincipalContext(

No comments: