![](/img/trans.png)
[英]How can I search for both the user's last name AND the first name in the Active Directory using C#
[英]Can I retrieve the domain name and user name by searching Active Directoy using C#
所有,
我有大量的用户电子邮件,我需要获取每个用户的用户名和域名。
我的组织包含许多域,我们的用户使用与电子邮件地址不同的用户名登录计算机。
请告知我们是否可以编写一个C#实用程序来使用每个用户的电子邮件来搜索AD,或者是否可以通过一种更简单的方式来进行搜索。
如果该数据全部包含在AD中,那么您可能可以使用LDAP查询它。 在这种情况下,由于您使用的是.NET,因此我建议您使用DirectorySearcher 。
您是否在.NET 3.5上? 如果是这样-AD 在.NET 3.5中具有重要的新功能-请查看Ethan Wilanski和Joe Kaplan撰写的本文《 在.NET 3.5中管理目录安全主体》 。
最大的新功能之一是“ PrincipalSearcher”类,该类应大大简化在AD中查找用户和/或组的过程。
如果无法使用.NET 3.5,请使用DirectorySearcher并指定电子邮件地址作为搜索条件,然后检索用户名(哪个?有成千上万种不同的用户名!):
DirectoryEntry deRoot = new DirectoryEntry("LDAP://cn=Users,dc=yourdomain,dc=com");
DirectorySearcher deSrch = new DirectorySearcher(deRoot);
deSrch.SearchScope = SearchScope.Subtree;
deSrch.PropertiesToLoad.Add("sn"); // surname = family name
deSrch.PropertiesToLoad.Add("givenName");
deSrch.PropertiesToLoad.Add("samAccountName");
deSrch.Filter = string.Format("(&(objectCategory=person)(mail={0}))", emailAddress);
foreach(SearchResult sr in deSrch.FindAll())
{
// you can access the properties of the search result
if(sr.Properties["sn"] != null)
{
string surname = sr.Properties["sn"][0].ToString();
}
// and so on, for all the other properties, too
}
希望这可以帮助!
渣
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.