Eran Kampf
Eran Kampf
1 min read

[Code snippet] Obtaining Active Directory User Information Using System.DirectoryServices

Here’s a snippet I wrote recently to read a user’s information (name, phone etc.) from the active directory:

public static string GetUserInfo(string user, string propertyName)
{
  DirectoryEntry adRootDSE = new DirectoryEntry("LDAP://rootDSE");
  DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + (string)adRootDSE.Properties["defaultNamingContext"].Value);
  DirectorySearcher searcher = new DirectorySearcher(adRoot);
  searcher.Filter = (&(objectClass=user)(samAccountName= + user + ));
  SearchResult result = searcher.FindOne();

  if (result == null) {
    return null;
  }


  ResultPropertyValueCollection values = result.Properties[propertyName];

  return ((values != null) && (values.Count > 0)) ? values[0].ToString() : null;
}

Example use for this function:

string firstName = ActiveDirectory.GetUserInfo(userName, givenName);
string middleName = ActiveDirectory.GetUserInfo(userName, middleName);
string lastName = ActiveDirectory.GetUserInfo(userName, sn);
string primaryMail = ActiveDirectory.GetUserInfo(userName, mail);
string secondaryMail = ActiveDirectory.GetUserInfo(userName, otherMailbox);
string phoneWork = ActiveDirectory.GetUserInfo(userName, telephoneNumber);
string phoneHome = ActiveDirectory.GetUserInfo(userName, homePhone);
string phoneMobile = ActiveDirectory.GetUserInfo(userName, mobile);
string phonePager = ActiveDirectory.GetUserInfo(userName, pager);
string fax = ActiveDirectory.GetUserInfo(userName, facsimileTelephoneNumber);
string www = ActiveDirectory.GetUserInfo(userName, wwwHomePage);
string company = ActiveDirectory.GetUserInfo(userName, company);
string department = ActiveDirectory.GetUserInfo(userName, department);

Security note:
This code requires Full Trust for the immediate caller and cannot be used by partially trusted code.

Update: Note that DirectoryEntry implements IDisposable and I am not disposing them in my code.
I should have used using statements here…