Reputation: 41
I'm trying to write a code that retrieves a user's email from the LDAP server. The user's email is in the 'mail' property, however, everytime I run it, the email returns "System.DirectoryServices.ResultPropertyValueCollection" instead of the user's email. Here is my code:
using (HostingEnvironment.Impersonate())
{
string server = "hello.world.com:389";
string email = null;
DirectoryEntry dEntry = new DirectoryEntry("LDAP://" + server + "/DC=hello,DC=world,DC=com");
DirectorySearcher dSearch = new DirectorySearcher(dEntry);
dSearch.SearchScope = SearchScope.Subtree;
dSearch.Filter = "(&(objectClass=users)(cn=" + lanID + "))";
dSearch.PropertiesToLoad.Add("mail");
SearchResult result = dSearch.FindOne();
if (result != null)
{
email = result.Properties["mail"].ToString();
return email;
}
else return email = null;
}
The code takes a user's employee id (lanID) and returns that userID's email (the value under 'mail' property). How should I do so I don't get System.DirectoryServices.ResultPropertyValueCollection but an actual email?
Upvotes: 4
Views: 12960
Reputation: 19168
You need to use SearchResult.GetDirectoryEntry()
Method to get the directory entry which corresponds to this SearchResult.
Retrieves the DirectoryEntry that corresponds to the SearchResult from the Active Directory Domain Services hierarchy. Use GetDirectoryEntry when you want to look at the live entry instead of the entry that was returned through DirectorySearcher, or when you want to invoke a method on the object that was returned.
--emphasis mine.
Use the below code:
DirectoryEntry user = result.GetDirectoryEntry();
string distinguishedName = user.Properties["mail"].Value.ToString();
Upvotes: 5
Reputation: 274
This means you are trying to convert an entire object to a string.
Change
email = result.Properties["mail"].ToString();
To this
email = result.Properties["mail"].Value.ToString();
Upvotes: 0