If i wanted to pull information about a user from Active Directory in .NET, i could use the DirectorySearcher
class.
For example, to find the e-mail address of a user i would call:
public String GetUserEmailAddress(String accountName)
{
DirectorySearcher searcher = new DirectorySearcher();
searcher.Filter = String.Format("(&(objectCategory=user)(sAMAccountName={0}))", accountName);
searcher.PropertiesToLoad.Add("mail");
SearchResult searchResult = searcher.FindOne();
return searchResult.Properties["mail"][0];
}
What is the native way to query the Active Directory?
Note:
- no domain name is specified
- no server name is specified
We can even extend our function to allow querying of any generic arbitrary information:
public Object GetUserAttribute(String accountName, String propertyName)
{
DirectorySearcher searcher = new DirectorySearcher();
searcher.Filter = String.Format("(&(objectCategory=user)(sAMAccountName={0}))", accountName);
searcher.PropertiesToLoad.Add(propertyName);
SearchResult searchResult = searcher.FindOne();
return searchResult.Properties[propertyName][0];
}
AD has all kinds of information that you can pass as propertyName
. For example:
displayName
(Display-Name): The display name for an object. This is usually the combination of the users first name, middle initial, and last name. (e.g. Ian A. Boyd)mail
(E-mail-Addresses): The list of email addresses for a contact. (e.g. ianboyd@stackoverflow.com)cn
(Common-Name): The name that represents an object. Used to perform searches.name
(RDN): The Relative Distinguished Name of an object. (e.g. Ian Boyd)sn
(Surname): This attribute contains the family or last name for a user.givenName
(Given-Name): Contains the given name (first name) of the user.sAMAccountName
(SAM-Account-Name): The logon name used to support clients and servers running older versions of the operating system, such as Windows NT 4.0, Windows 95, Windows 98, and LAN Manager. This attribute must be less than 20 characters to support older clients.objectGUID
(Object-Guid): The unique identifier for an object. (e.g. {3BF66482-3561-49a8-84A6-771C70532F25})employeeID
(Employee-ID): The ID of an employee. /// "description" (Description): Contains the description to display for an object. This value is treated as single-valued by the system.