按名字和姓氏搜索用户登录 ID
本文关键字:搜索 用户 登录 ID | 更新日期: 2023-09-27 18:31:51
我找到了如何从活动目录中获取用户列表?
当我只有几个用户,但我在 AD 中有这么多用户时,这很有帮助,所以当我运行查询时
if ((String)(entry.Properties["sn"].Value) == "lname"
&& (String)(entry.Properties["givenName"].Value) == "fname")
{
return entry.Properties["samAccountName"].Value.ToString();
}
花了太长时间才完成。
如何按名字和姓氏搜索特定用户登录 ID?
由于使用的是 .NET 4,因此应签出 System.DirectoryServices.AccountManagement
(S.DS.AM) 命名空间。在这里阅读所有关于它的信息:
- 在 .NET Framework 3.5 中管理目录安全主体
- MSDN 文档 on System.DirectoryServices.AccountManagement
基本上,您可以定义域上下文并在 AD 中轻松查找用户和/或组:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user - by e.g. his "samAccountName", or the Windows user name or something
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// do something here....
string samAccountName = user.SamAccountName;
}
如果找不到由用户名指定的用户,还可以使用新的搜索功能:
// define a "query-by-example" principal - here, we search for a UserPrincipal
// and with the first name (GivenName) and a last name (Surname)
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.GivenName = firstName;
qbeUser.Surname = lastName;
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
}
新的 S.DS.AM 让在AD中玩用户和组变得非常容易!而且仅仅找到一个用户也应该相对较快。
您应该使用 AD 服务器进行过滤。通过提供 LDAP 语法筛选器来执行此操作。此外,仅使用 FindAll
的 propertiesToLoad
参数指定所需的属性:
public static SearchResultCollection FindByName(
string domain, string firstName, string lastName, string[] properties) {
var rootEntry = new DirectoryEntry("LDAP://" + domain);
var filter = string.Format("(&(sn={0})(givenName={1}))", lastName, firstName);
var searcher = new DirectorySearcher(rootEntry, filter, properties);
return searcher.FindAll();
}
// Using the method:
var result = FindByName("mydomain", "Robert", "Smith", new[] { "samAccountName" })[0];
string uName = (string)result.Properties["samAccountName"][0];
您需要
在 searcher
上设置 QueryFilter 属性,然后调用 searcher.FindOne()
而不是 searcher.FindAll()
。 可以将查询筛选器设置为 UserPrincipal 对象,您可以在其中设置要搜索的字段。
Microsoft在"按示例查询"页面上有一个很好的例子,尽管他们的示例希望找到与给定条件匹配的多个对象。
根据您的要求对链接问题进行特别字面的改编将是
using (var context = new PrincipalContext(ContextType.Domain, "mydomain.com"))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context) { GivenName = "fname", Surname = "lname" }))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
return de.Properties["samAccountName"].Value.ToString();
}
}
}
如果entry
是IEnumerable
集合的一部分,则可以执行以下操作:
var entries = {do your population of the collection here}
var entry = entries.Where(e=>e.Properties["sn"].Value.ToString() == "lname"
&& e=>.Properties["givenName"].Value.ToString() == "fname")
.FirstOrDefault();