2013-12-13 154 views
-1

有誰知道在Active Directory中使用DirectoryServices搜索單個用戶的最佳方法嗎?我有代碼,目前列出給定的LDAP路徑下的所有子'OU',但我現在想要添加搜索路徑下的用戶的功能。代碼是否適合搜索用戶?ASPX C#在Active Directory中搜索用戶

我已經包含了我的代碼,列出了所有用戶在當前的OU:

DirectoryEntry Ldap = new DirectoryEntry("LDAP://" + ouselect.SelectedValue + ";" + LDAPRoot, LDAPUser, LDAPPass); 
DirectorySearcher ad_search = new DirectorySearcher(Ldap); 

ad_search.Filter = "(objectClass=User)"; 
ad_search.SearchScope = SearchScope.Subtree; 
ad_search.PropertiesToLoad.Add("samaccountname"); 

任何指針任何人都可以提供將是極好的。

回答

2

如果您使用.NET 3.5及更高版本,則應檢查System.DirectoryServices.AccountManagement(S.DS.AM)命名空間。在這裏閱讀全部內容:

基本上,你可以定義域範圍內,並可以輕鬆地查找用戶和/或組AD:

// set up domain context 
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) 
{ 
    // find a user 
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName"); 

    if(user != null) 
    { 
     // do something here....  
    } 
} 

的新的S.DS.AM可以很容易地與AD中的用戶和羣組玩耍!

PS:PrincipalContext對其構造函數有許多不同的重載 - 您還可以定義用於查詢Active Directory的用戶名/密碼,並且還可以定義一個「起始」容器(如果需要)。 Check out the MSDN documentation for details on this

0

你的代碼幾乎在那裏。只需更改過濾器即可搜索特定的AD屬性,而不是所有用戶。

ad_search.Filter = string.Format("(department={0})", department);

ad_search.Filter = string.Format("(displayName={0})", "James Doe");

ad_search.Filter = string.Format("(sAMAccountName={0})", "some.username");

+1

你還是會希望包括過濾器的基礎對象類的組成部分。 –

相關問題