简体   繁体   中英

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?

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();

用这个:

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

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();

这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM