get ldap for employeeid in csharp

Here's an example code snippet that demonstrates how to query Active Directory and retrieve employeeid using LDAP in C# using DirectorySearcher class from System.DirectoryServices:

using System.DirectoryServices;

public static string GetEmployeeId(string username, string domain, string ldapPath) {
    string result = string.Empty;
    try {
        DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://" + domain + "/" + ldapPath);
        DirectorySearcher searcher = new DirectorySearcher(directoryEntry);
        searcher.Filter = "(samAccountName=" + username + ")";
        searcher.PropertiesToLoad.Add("employeeID");
        SearchResult searchResult = searcher.FindOne();
        if(searchResult != null) {
            result = searchResult.Properties["employeeID"][0].ToString();
        }
    } catch(Exception ex) {
        //handle exception
    }
    return result;
}
709 chars
19 lines

You can pass in the username, domain and ldapPath parameters to the method to retrieve the employeeid for that specific user from the Active Directory.

gistlibby LogSnag