18

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

我可以根据sAMAccountname以下代码找到用户:

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

 SearchResult results1;
 results1 = searcher1.FindOne();

但是当我尝试使用givenNameand来做到这一点时sn

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

SearchResultCollection results1;
results1 = searcher1.FindAll();

它不起作用;消息显示“过滤器无效”;我不能根据givenNameand过滤sn吗?

我怎样才能做到这一点?

4

3 回答 3

31

如果您使用的是 .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,它很好地展示了如何充分利用 .NET Framework 中的新功能System.DirectoryServices.AccountManagement。或查看System.DirectoryServices.AccountManagement命名空间上的 MSDN 文档。

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

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

您可以在 上指定任何属性UserPrincipal并将其用作PrincipalSearcher.

于 2012-03-07T15:22:13.297 回答
13

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

searcher1.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(givenname={0})(sn={1}))", aName, aSName);
于 2012-03-07T15:09:02.163 回答
0

没办法这是一个错误..

我忘了一个)

于 2012-03-07T15:10:12.490 回答