gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:58:22 24 4
gpt4 key购买 nike

我正在尝试编写一段代码,从 LDAP 服务器检索用户的电子邮件。用户的电子邮件位于“邮件”属性中,但是,每次我运行它时,电子邮件都会返回“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) 并返回该用户 ID 的电子邮件(“邮件”属性下的值)。我应该怎么做才能得到 System.DirectoryServices.ResultPropertyValueCollection 而不是实际的电子邮件?

最佳答案

您需要使用 SearchResult.GetDirectoryEntry()获取与此 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.

使用下面的代码:

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

关于c# - 如何使用 Active Directory 从属性中检索值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47658225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com