Active Directory Lookup (C#)

I very quickly needed to get some user data out of Active Directory, which I’ve done plenty of times before, but I’d forgotten how to do it, so decided to ignore previous code and try and do it again – and also document it here for my own purposes.

1. Add the .Net assembly System.DirectoryServices and add the using statement.

2. Then add the following code:

DirectoryEntry entry = new DirectoryEntry();
 DirectorySearcher searcher = new DirectorySearcher(entry);
 searcher.Filter = ("(sAMAccountName=" + username + ")");

foreach (SearchResult result in searcher.FindAll())
Console.Write(result.Properties["givenName"][0] as string);
 Console.Write(result.Properties["sn"][0] as string);
 Console.Write(result.Properties["mail"][0] as string);

Byte[] bArr = (Byte[])result.Properties["objectGUID"][0];


3. The GetGuid() method converts the Byte array returned to a string, and looks like this:

string guid = "";
 foreach (Byte b in bArr)
 guid += b.ToString("x2");
 return guid;


4 thoughts on “Active Directory Lookup (C#)

  1. I had been searching for hours. Line 14 from your example above solved my problem. Thank you!

    This is the function I used to convert the objectGUID to string and display it as it is shown in Active Directory Users and Computers console–>User property–>Attribute Editor–>objectGUID.

    Byte[] bArr = (Byte[])_ldapResult[0].Properties[“objectGUID”][0];
    userGUID.Text = getGUID(bArr);

    public string getGUID(byte[] byteArray)
    Guid objectGuid = new Guid(byteArray);
    return objectGuid.ToString();

    many thanks….

  2. Thanks a lot, this is exactly what I was looking for. I used a StringBuilder to be a little faster in converting the GUID :

    StringBuilder guid = new StringBuilder();
    foreach (Byte b in bArr)
    return guid.ToString();

    The above use of the GUID object will return the value seen in the AD attribute editor with the dashes, I needed the HEX value shown and this was the way to do it

  3. Thanks for the info. I was searching it across the internet and was getting result in PowerShell only. Thanks for sharing the example in C#.

    Can you also explain the working of GetGuid() method, especially b.ToString(“x2”). what is x2 here?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s