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, "yourdomain.com");
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();
search.Dispose();

if (user != null) {
   Console.WriteLine(user.DistinguishedName);
} 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:
corp.xxx.com
  - domain1.corp.xxx.com
  - domain2.corp.xxx.com
  - ...
To search across all children of the corp.xxx.com domain construct your PrincipalContext like this:
var context = new PrincipalContext(
                      ContextType.Domain,
                      "corp.xxx.com:3268",
                      "DC=corp,DC=xxx,DC=com");

No comments: