我有一个函数用于查找与给定名称匹配的任何用户的 displayName 和 mail 字段。到目前为止它有效,但它只返回我登录的用户。
我已经尝试过不同版本的DirectorySearcher
,如下所示:
new DirectorySearcher("LDAP://my.domain");
new DirectorySearcher();
new DirectorySearcher("LDAP://my.domain/(&(objectCategory=person)(objectClass=user)(anr={0}))");
我还尝试了不同的路径格式和 AuthenticationTypes。
我的功能:
/// <summary>
/// Returns a Dictionary of Names and Emails that match the given name
/// </summary>
/// <param name="name">Name to search for</param>
/// <param name="domain">Domain to log in to</param>
/// <param name="username">Username for login into AD</param>
/// <param name="pwd">Password for login into AD</param>
/// <param name="count">returns the number of results found</param>
/// <returns>Dictionary containing the Names and Emails of the users matched</returns>
public Dictionary<string, string> GetPersonsEmailsByName(string name, string domain, string username, string pwd, out int count)
{
count = 0;
if (String.IsNullOrEmpty(name)) return new Dictionary<string, string>();
try
{
string domainAndUsername = String.Format(@"{0}\{1}", domain, username);
using (DirectoryEntry root = new DirectoryEntry("LDAP://my.domain", domainAndUsername, pwd, AuthenticationTypes.Delegation))
{
DirectorySearcher search = new DirectorySearcher(root);
search.Filter = String.Format("(&(objectCategory=person)(objectClass=user)(anr={0}))", name);
search.SearchScope = SearchScope.Subtree;
search.PropertiesToLoad.Add("displayName");
search.PropertiesToLoad.Add("mail");
var dict = new Dictionary<string, string>();
SearchResultCollection result = search.FindAll();
count = result.Count;
foreach (SearchResult sr in result)
{
var de = sr.GetDirectoryEntry();
dict.Add((string)de.Properties["displayName"].Value, (string)de.Properties["mail"].Value);
}
return dict;
}
}
catch (Exception ex)
{
throw new Exception("Error obtaining persons: " + ex.Message);
}
}
这是使用此函数的示例输出:
User: john_doe
Pass:
Auth OK
Name: Mike
Results: 0
Name: carl
Results: 0
Name: jo
Results: 1
John Doe: j_doe@domain.com
Name: john
Results: 1
John Doe: j_doe@domain.com
Name: j
Results: 1
John Doe: j_doe@domain.com
Name:
我能得到的只是我自己的名字。
在此先感谢您的帮助。