Wednesday, June 13, 2012

Programmatically obtain a list of all properties associated with a user's profile in Active Directory

The following simplified code sample can be used for obtaining a list of all possible properties that are associated with a user's profile in Active Directory.  This code would be useful if you're trying to figure out which AD properties you may need to access to get the information you require:


using System.DirectoryServices;

...

try
{
   using (DirectoryEntry dirEntry = new DirectoryEntry("LDAP://yourOUPath))
   {
      using (DirectorySearcher dirSearch = new DirectorySearcher(dirEntry))
      {
         dirSearch.Filter = "(&(objectClass=user)(sAMaccountname=yourADLoginName))";
         SearchResult result = dirSearch.FindOne();
         if (result != null)
         {
            foreach (string propertyName in result.Properties.PropertyNames)
            {
               Console.WriteLine(propertyName);
            }
         }
      }
   }
}
catch (Exception ex)
{
   Console.WriteLine(ex.Message);
}


Likely culprits for issues with this code could be attributed to the following items:
  1. There could be issues with the structure of the LDAP path
  2. You may need to specify a DirectoryEntry.Username and DirectoryEntry.Password
  3. You may need to define a DirectoryEntry.AuthenticationType


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.