I’d like to do a LDAP query against AD to pull a user’s location (city). This is what I’ve put together:
public static string GetUserLocation(string userName)
{
string userLoc = "";
DirectoryEntry entry = new DirectoryEntry("LDAP://FTLAD04.corp.myDomain.com");
DirectorySearcher dSearch = new DirectorySearcher(entry);
dSearch.Filter = "(&(objectClass=user)(l=" + userName + "))";
dSearch.PropertiesToLoad.Add("city");
SearchResult result = dSearch.FindOne();
userLoc = result.ToString();
entry.Close();
return userLoc;
}
My SearchResult keeps coming back null, can anyone help point me in the right direction? Thank you!
I think your error is that you’re searching for the location, but setting the user name as the value…
You should search for the user’s name – and grab the location for that user:
In AD, the user’s City (that you enter in the Active Directory Users & Computers tool) is stored in the
lattribute of theDirectoryEntry.For a complete list of all attributes and how they map from the ADU&C tool to actual LDAP objects and attributes, see Robert Mueller’s web site