J Kang
J Kang

Reputation: 41

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?

Upvotes: 4

Views: 12960

Answers (4)

Willy
Willy

Reputation: 146

This:

email = result.getdirectoryentry.properties("mail").value 

Upvotes: 0

Abhi
Abhi

Reputation: 29

Use this:

(String)user.Properties["mail"][0];

Upvotes: 2

Am_I_Helpful
Am_I_Helpful

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

Alex
Alex

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

Related Questions