如何使用Active Directory从属性中检索值?

时间:2017-12-05 16:24:18

标签: c# visual-studio-2015 active-directory ldap

我正在尝试编写一个从LDAP服务器检索用户电子邮件的代码。用户的电子邮件位于“mail”属性中,但是,每次运行时,电子邮件都会返回“System.DirectoryServices.ResultPropertyValueCollection”而不是用户的电子邮件。这是我的代码:

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;
        }

代码获取用户的员工ID(lanID)并返回该userID的电子邮件(“mail”属性下的值)。我该怎么办?我没有获得System.DirectoryServices.ResultPropertyValueCollection但是实际的电子邮件?

3 个答案:

答案 0 :(得分:0)

这意味着您正在尝试将整个对象转换为字符串。

更改

email = result.Properties["mail"].ToString();

到此

email = result.Properties["mail"].Value.ToString();

答案 1 :(得分:0)

您需要使用SearchResult.GetDirectoryEntry()方法获取与此SearchResult对应的目录条目。

  

检索与SearchResult对应的DirectoryEntry   Active Directory域服务层次结构。 如果要查看实时条目而不是通过DirectorySearcher返回的条目,或者要在返回的对象上调用方法,请使用GetDirectoryEntry。    - 强调我的。

使用以下代码:

DirectoryEntry user = result.GetDirectoryEntry();
string distinguishedName = user.Properties["mail"].Value.ToString();

答案 2 :(得分:0)

使用此:

(String)user.Properties["mail"][0];
相关问题