If you are writing a program that leverages Active Directory then there may be times where you want to retrieve the current user's AD object. It can be handy for situations where you need the user's email address, account information, or some other piece of data stored in the directory. Below is a code snippet to retrieve the current user object as well as translate an NT domain name into a distinguished name all through managed code (as opposed to DsCrackNames which uses RPC and interop).
public static DirectoryEntry CurrentUser
{
get
{
string[] currentUserName = WindowsIdentity.GetCurrent().Name.Split('\\');
string domainDistinguishedName = GetDistinguishedName(currentUserName[0]);
DirectoryEntry domain = new DirectoryEntry("LDAP://" + domainDistinguishedName);
DirectorySearcher searcher = new DirectorySearcher(domain,
String.Format("(sAMAccountName={0})", currentUserName[1]));
SearchResult result = searcher.FindOne();
DirectoryEntry currentUser = null;
if (result != null)
{
currentUser = result.GetDirectoryEntry();
}
return currentUser;
}
}
public static string GetDistinguishedName(string netbiosName)
{
if (string.IsNullOrEmpty(netbiosName))
{
throw new ArgumentNullException("netbiosName");
}
if (!Regex.IsMatch(netbiosName, @"^[-\w]{1,15}$"))
{
throw new ArgumentException("Invalid NetBIOS domain name format. Domain name should be a maximum of 15 alphanumeric characters (including dashes).", "netbiosName");
}
DirectoryEntry globalCatalog = new DirectoryEntry("LDAP://RootDSE");
string configurationPath = (string)globalCatalog.Properties["configurationNamingContext"].Value;
DirectoryEntry partitions = new DirectoryEntry("LDAP://CN=Partitions," + configurationPath);
DirectorySearcher searcher = new DirectorySearcher(partitions,
String.Format("(&(objectClass=crossRef)(nETBIOSName={0}))", netbiosName),
new string[] { "nCName" },
SearchScope.OneLevel);
SearchResult result = searcher.FindOne();
string distinguishedName = null;
if (result != null)
{
distinguishedName = result.Properties["nCName"][0] as string;
}
return distinguishedName;
}
From there you can easily retrieve the user's email address:
Console.WriteLine(CurrentUser.Properties["mail"].Value as string);
Enjoy!