A simple method for finding Active Directory user information using C# with LDAP
I spent hours trying to find a simple way to get user data our of AD from an LDAP query. Turns out you don't need to do a lot of crazy stuff, and looking at my code when I was done, it turned out to be a lot easier than it seemed when I started out.
The only thing I need to pass in to my function was the name of the property (see the list here), and the username. In my case it was coming from some other logic I had to write to get the users of a group that was a member of a SharePoint site.
Also the ldapPath I pass in to the DirectorySearcher constructor was simply "LDAP://mydomain.com"
This returns the value of the property of the user that you specify as a string. Example:
getValidADProps("mail", "Ima User") will return the AD email address for Ima User.
In the function, I used a try/catch in the instance that the property you are trying to find isn't there, you will get a index out of range error.
I will say that this is not the more lightweight method, according to my findings. For a more specific return set from the searcher you may want to look into the PropertiesToLoad Property of the class.
public string getValidADProps(string _prop, string _username)
{
DirectorySearcher ds = new DirectorySearcher(ldapPath);
ds.SearchScope = SearchScope.Subtree;
ds.Filter = "samaccountname=" + _username;
SearchResult sr = ds.FindOne();
try
{
if (!string.IsNullOrEmpty(sr.Properties[_prop][0].ToString()))
{
return sr.Properties[_prop][0].ToString();
}
}
catch (Exception)
{
return string.Empty;
}
return string.Empty;
}
HTH,
Eric
Comments
Post a Comment