【问题标题】:How can I search users in Active Directory based on surname and first name? [closed]如何根据姓氏和名字在 Active Directory 中搜索用户? [关闭]
【发布时间】:2012-03-07 15:04:15
【问题描述】:

我正在尝试使用 .NET 中的 DirectorySearcher 在 AD 中搜索姓氏 (sn) 和名字 (givenName) 的用户。

我可以使用此代码找到基于sAMAccountname 的用户:

 DirectorySearcher searcher1 = new DirectorySearcher(entry);
 searcher1.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(SAMAccountname={0}))",aLogin);

 SearchResult results1;
 results1 = searcher1.FindOne();

但是当我尝试用givenNamesn 来做这件事时:

DirectorySearcher searcher1 = new DirectorySearcher(entry);
searcher1.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(givenname={0})(sn={1})", aName, aSName);

SearchResultCollection results1;
results1 = searcher1.FindAll();

它不起作用;消息显示“过滤器无效”; 我可以不根据givenNamesn 过滤吗?

我怎样才能做到这一点?

【问题讨论】:

  • 我发现这个问题通常很有用,没有具体的错字问题

标签: c# active-directory directorysearcher


【解决方案1】:

如果您使用的是 .NET 3.5 或更高版本,您还可以使用 PrincipalSearcher 和“按示例查询”主体进行搜索:

// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// define a "query-by-example" principal - here, we search for a UserPrincipal 
// and with the first name (GivenName) of "Bruce" and a last name (Surname) of "Miller"
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.GivenName = "Bruce";
qbeUser.Surname = "Miller";

// 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.....          
}

如果您还没有 - 一定要阅读 MSDN 文章 Managing Directory Security Principals in the .NET Framework 3.5,它很好地展示了如何充分利用 System.DirectoryServices.AccountManagement 中的新功能。或查看MSDN documentation on the System.DirectoryServices.AccountManagement 命名空间。

当然,根据您的需要,您可能希望在您创建的“示例查询”用户主体上指定其他属性:

  • DisplayName(通常:名字 + 空格 + 姓氏)
  • SAM Account Name - 您的 Windows/AD 帐户名
  • User Principal Name - 您的“username@yourcompany.com”样式名称

您可以在UserPrincipal 上指定任何属性并将其用作PrincipalSearcher 的“示例查询”。

【讨论】:

  • 在本例中,您可以在哪里指定 AD 连接字符串 - 用户名/密码等?
  • @PandaWood:PrincipalContext 有几个重载的构造函数来支持这一点
【解决方案2】:

您的过滤器中缺少右括号。试试:

searcher1.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(givenname={0})(sn={1}))", aName, aSName);

【讨论】:

    【解决方案3】:

    这绝不是错误..

    我忘记了)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 2018-09-02
      • 2011-08-19
      • 1970-01-01
      • 2016-09-28
      相关资源
      最近更新 更多