How to get the current user's Active Directory details in C#

Sophia picture Sophia · Mar 12, 2009 · Viewed 136.2k times · Source

I am working on an C# and ASP.Net application, that uses Windows Authentication.

i.e. in Web.config:

<system.web>
    <authentication mode="Windows" />
</system.web>

I want to get details for the current user (full name, email address, etc) from Active Directory.


I can get their pre Windows 2000 user login name (eg: SOMEDOMAIN\someuser) by using

string username = HttpContext.Current.Request.ServerVariables["AUTH_USER"];

I've worked out the LDAP query for the user, using their current login name (not their pre Windows 2000 user login name):

DirectorySearcher adSearch = new DirectorySearcher(
        "([email protected])");
SearchResult adSearchResult = adSearch.FindOne();

However, I don't know how to either search AD for the user using their pre W2K login name, or get their login name in the '[email protected]' format.

Any ideas?

Answer

Alan picture Alan · Mar 12, 2009

The "pre Windows 2000" name i.e. DOMAIN\SomeBody, the Somebody portion is known as sAMAccountName.

So try:

using(DirectoryEntry de = new DirectoryEntry("LDAP://MyDomainController"))
{
   using(DirectorySearcher adSearch = new DirectorySearcher(de))
   {
     adSearch.Filter = "(sAMAccountName=someuser)";
     SearchResult adSearchResult = adSearch.FindOne();
   }
}

[email protected] is the UserPrincipalName, but it isn't a required field.