Using LDAP to locate a user name

I found myself needing to extract the current user’s full name from our Active Directory today. For a variety of reasons, I’ve not done too much work in this area, so I had to hunt around for a few minutes before arriving at a solution.

Firstly, I had to add a reference to System.DirectoryServices to my project – no problem, right click on the References node in Visual Studio and choose Add Reference. Secondly, I had to add using System.DirectoryServices to my source code.

Anyway, here’s the C# code that I used – note the use of the UserName property from the Environment class.

using System.DirectoryServices;
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://dc=DOMAIN_CONTEXT,dc=com");
DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry);
directorySearcher.Filter = "(&(objectCategory=person)(sAMAccountName=" + Environment.UserName + "))";
DirectoryEntry result = directorySearcher.FindOne().GetDirectoryEntry();

string name = result.Properties["displayName"].Value.ToString();

In my case, the username CMurphy became Craig Murphy (displayName). Your properties may vary, and you’ll need to know your own domain context (dc).