AD Property Lister

Custom made windows applications has become something I´ve been using more often in web projects to test functionality, migrate data or just extract information from a specific environment. It has helped to speed up the development, structure the project and make some parts easier to built.

So here´s a tip to query the AD hierarchy for a specific user, extract all properties and output its name and corresponding value to the console. Note: LDAP is the only system-supplied provider that supports directory searching.

// Contants used by the DirectoryEntry component instance.
// The credentials must have rights to access information 
// in Active Directory Domain Services.
const string ADPath = "LDAP://domain.mycompany.local";
const string ADUserName = "domain\\user";
const string ADPassword = "My.Password";
 
/// <summary>
/// Performs a search against the Active Directory for a specific person 
/// using the supplied username.
/// </summary>
static void PrintUserProperties(string username)
{
    using (DirectoryEntry entry = CreateDirectoryEntry())
    using (DirectorySearcher searcher = GetDirectorySearcher(entry, username))
    {
        SearchResult result = searcher.FindOne();
 
        if (result != null)
        {
            ResultPropertyCollection ldapFields = result.Properties;
 
            foreach (string field in ldapFields.PropertyNames)
            {
                foreach (object myCollection in ldapFields[field])
                {
                    Console.WriteLine(string.Format("{0,-20} : {1}", field, myCollection.ToString()));
                }
            }
        }
        else
        {
            Console.WriteLine("User not found!");
        }
    }
}
 
/// <summary>
/// Creates and returns a directory entry component instance.
/// </summary>
static DirectoryEntry CreateDirectoryEntry()
{
    var entry = new DirectoryEntry()
    {
        Path = ADPath,
        Username = ADUserName,
        Password = ADPassword,
        AuthenticationType = AuthenticationTypes.None
    };
 
    return entry;
}
 
/// <summary>
/// Gets a DirectorySearcher instance to perform queries against 
/// the AD hierarchy.
/// </summary>
static DirectorySearcher GetDirectorySearcher(DirectoryEntry directoryEntry, string username)
{
    var searcher = new DirectorySearcher()
    {
        SearchRoot = directoryEntry,
        Filter = string.Format("(&(sAMAccountName={0})(objectCategory=person))", username)
    };
 
    return searcher;
}