111,094
社区成员




DirectoryEntry entry = new DirectoryEntry("LDAP://" + Domain.GetCurrentDomain());
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = "(&(objectClass=user)(displayname=" + user.Name + "))"; //user表示用户,group表示组
mySearcher.PropertiesToLoad.Add("userPrincipalName");
mySearcher.PropertiesToLoad.Add("department");
mySearcher.PropertiesToLoad.Add("mail");
mySearcher.PropertiesToLoad.Add("title");
try
{
var result = mySearcher.FindOne();
if (result != null)
{
if (result.Properties.Contains("mail"))
{
user.Email = result.Properties["mail"][0].ToString();
}
else
{
user.Email = "null@null.com";
}
if (result.Properties.Contains("department"))
{
Department = result.Properties["department"][0].ToString().ToLower();
}
if (result.Properties.Contains("title"))
{
title = result.Properties["title"][0].ToString().ToLower();
}
}
}
catch(Exception e)
{
user.Email = "fail ad search";
throw;
}
});
我因为个人的需求,在生成DirectoryEntry时不需要提供账号密码,但是跨域查询据我经验来看提供异域的AD用户的账号密码是解决问题的捷径。
Searcher.filter指定的就是在域里搜索的条件。此时因为未设置pagesize,最多只可得到1000条数据,随意设置pagesize后可获取更多数据。个人亲测,设置pagesize=1000,取得6000+条数据。只是我用了这么点而已。
PropertiesToLoad.add添加的是从ad中获取的属性,如果不指定,默认取得adpath属性和一个什么属性(忘记了)。