2012-03-07 54 views
12

我正在尝试使用.net DirectorySearcher搜索AD中用户的姓名和名字。如何根据名称和名字搜索活动目录中的用户

在事实,我可以找到基于SAM帐户通过使这样的:

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

SearchResult results1; 
results1 = searcher1.FindOne(); 

但是,当我试图做到这一点:

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

SearchResultCollection results1; 
results1 = searcher1.FindAll(); 

它不工作。该消息显示“Invalid Filter” 所以我不能根据给定名称和sn?进行过滤

我该如何做到这一点? 感谢您的帮助

+0

??一年后进行投票?为什么? – bAN 2013-03-01 14:40:37

+1

我发现这个问题一般有用,没有具体的错字问题 – PandaWood 2016-04-05 06:58:10

回答

7

您错过了过滤器中的圆括号。尝试:

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

没办法,这是一个错误..

我忘了)

23

如果您使用.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 - 你的 “[email protected]” 样式名

可以SPE将UserPrincipal上的任何属性都作为属性,并将它们用作您的PrincipalSearcher的“查询范例”。

+0

感谢您的建议。我重构了我的所有代码 – bAN 2012-03-08 21:33:22

+0

该MSDN文章已被删除它似乎 – PandaWood 2016-04-05 06:38:42

+0

在这个例子中,你可以指定AD连接字符串 - 用户名/密码等? – PandaWood 2016-04-05 06:57:12