Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve a value from a property using Active Directory?

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?

like image 421
J Kang Avatar asked Sep 01 '25 16:09

J Kang


1 Answers

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();
like image 151
Am_I_Helpful Avatar answered Sep 04 '25 05:09

Am_I_Helpful