Monday 30 November 2009

Searching For users within an Active Directory group - .Net 3.5 Style!

In .Net 3.5, Microsoft has introduced a new library that makes search for users/groups etc in Active Directory a doodle.

This new namspace is :
System.DirectoryServices.AccountManagement

As an example of its flexibility i have included 2 examples:

Example 1: Getting a Principals' (user) Details from AD:
 using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "[ADSERVER]"))
{
Principal principal = Principal.FindByIdentity(ctx, IdentityType.SamAccountName, "[USERNAME]");
Console.WriteLine(principal.DisplayName);
}

Example 2: Getting All users belonging to an AD Group:
 using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "[AD SERVER]"))
{

GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(ctx,[GROUP DN or GROUP NAME]);

PrincipalSearchResult<Principal> results = groupPrincipal.GetMembers(true);

foreach (Principal p in results)
{
Console.WriteLine(p.Name);
}

}