使用C#中的DirectorySearcher来获得活动目录中的组织结构与用户等信息,并在展示成树形结构(附源代码)
对于C#来说,取得活动目录中的组织结构相对简单,因为其在System.DirectoryServices命名空间中内置了DirectorySearcher的方法,我们可以组合多种过滤方式,来达到取得活动目录中的所有信息,当然,我现在还没有找到可以得到域用户密码的方式 :)
以下是关键片段
1private 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 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 }
参数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" });
这一句是指对范围内的属性进行加载,以提高效率。
效果图
点击这里下载源代码