對於C#來說,取得活動目錄中的組織結構相對簡單,因為其在System.DirectoryServices命名空間中內置了DirectorySearcher的方法,我們可以組合多種過濾方式,來達到取得活動目錄中的所有信息,當然,我現在還沒有找到可以得到域用戶密碼的方式 :)
以下是關鍵片段
1
private static SearchResultCollection _ADHelper(string domainADsPath, string username, string password, string schemaClassNameToSearch)
2
{
3
DirectorySearcher searcher = new DirectorySearcher();
4
5
searcher.SearchRoot = new DirectoryEntry(domainADsPath,
6
username, password);
7
searcher.Filter = "(objectClass=" + schemaClassNameToSearch + ")";
8
9
searcher.SearchScope = SearchScope.Subtree;
10
searcher.Sort = new SortOption("name",
11
SortDirection.Ascending);
12
// If there is a large set to be return ser page size for a paged search
13
searcher.PageSize = 512;
14
15
searcher.PropertiesToLoad.AddRange(new string[] { "name", "Path", "displayname", "samaccountname", "mail" });
16
17
SearchResultCollection results = searcher.FindAll();
18
return results;
19
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

參數domainADsPath是活動目錄的域名,使用類似"LDAP://域名"的形式
參數schemaClassNameToSearch是過濾條件,基本上有以下三個選擇,更多選擇請參考微軟的網站
1. objectClass=organizationalUnit 查詢條件是所有的組織單元(OU)
2. objectClass=group 查詢條件是所有的組(GROUP)
3. objectClass=user 查詢條件是所有的用戶(USER)
searcher.PropertiesToLoad.AddRange(new string[] { "name", "Path", "displayname", "samaccountname", "mail" });
這一句是指對范圍內的屬性進行加載,以提高效率。
效果圖
點擊這里下載源代碼