2012-03-07 38 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

相關問題