User Search in AD

I stumbled upon the System.DirectoryServices.AccountManagement namespace this week. It was introduced with .Net 3.5 and offers functionality to perform queries on AD objects like users, groups and computers in a more comfortable way than through the DirectorySearcher class from the System.DirectoryServices namespace. To illustrate the ease of using these classes, I came up with a tiny example which lists all users whose account name (the samAccountName attribute in AD) starts with an 'a'. On top of this, using LINQ it is quite simple to convert the resulting PrincipalSearchResult<Principal> collection into an IEnumerable<UserPrincipal>.

using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;

namespace UserSearch
{
    class Program
    {
        static void Main(string[] args)
        {
            PrincipalContext context = new PrincipalContext(ContextType.Domain, "contoso.com");

            UserPrincipal searchFilter = new UserPrincipal(context);
            searchFilter.SamAccountName = "a*";

            PrincipalSearcher ps = new PrincipalSearcher(searchFilter);

            IEnumerable<UserPrincipal> results = from principal in ps.FindAll()
                                                 where principal is UserPrincipal
                                                 select principal as UserPrincipal;

            foreach (UserPrincipal user in results)
            {
                Console.WriteLine("User '{0}' ({1}) Info:", user.SamAccountName, user.Name);
                Console.WriteLine("    Password Set On  {0}", user.LastPasswordSet);
                Console.WriteLine("    Last Log On      {0}", user.LastLogon);
                Console.WriteLine();
            }
        }
    }
}