如何使用PrincipalContext

时间:2016-07-14 12:08:58

标签: c# active-directory directoryservices directoryentry account-management

 myUserList AppUsers = new myUserList();    
 using (PrincipalContext pcxt = new PrincipalContext(ContextType.Domain, domainName))
            {
                UserPrincipal User = new UserPrincipal(pcxt);
                User.EmailAddress = emailString;

                PrincipalSearcher srch = new PrincipalSearcher(User);
                foreach (var principal in srch.FindAll())
                {
                    var p = (UserPrincipal)principal;
                    myUserRow User = AppUsers.NewUsersRow();
                    User.FirstName = p.GivenName;
                    User.LastName = p.Surname;
                    User.Email = p.EmailAddress;
                    AppUsers.AddUsersRow(User);

                }
            }

我有类似上面的代码,使用PrincipalContext类在Active Directory中搜索用户信息。

正如您所见,我在搜索过程中传入了domainName。 我怎样才能修改这个代码的平静,而不是搜索整个森林(即全局目录),但仍然使用PrincipalContext类?

我似乎无法找到使用PrincipalContext类进行全局编录搜索的工作示例。

我看过这篇文章How to search for users in Global Catalog within AD forest with multiple trees,但海报似乎表明他们没有找到使用PrincipalContext类的解决方案,他们不得不切换回DirectorySearcher。

是否有任何PrincipalContext类代码示例演示在整个林中进行搜索(全局目录)?

1 个答案:

答案 0 :(得分:1)

好吧,我明白了。我只需要像下面那样更改我的代码。

 myUserList AppUsers = new myUserList();    
 using (PrincipalContext pcxt = new PrincipalContext(ContextType.Domain,  "my-global-catalogue-server.subdomain.domain.com:port", "DC=subdomain,DC=domain,DC=com"))
            {
                UserPrincipal User = new UserPrincipal(pcxt);
                User.EmailAddress = emailString;

                PrincipalSearcher srch = new PrincipalSearcher(User);
                foreach (var principal in srch.FindAll())
                {
                    var p = (UserPrincipal)principal;
                    myUserRow User = AppUsers.NewUsersRow();
                    User.FirstName = p.GivenName;
                    User.LastName = p.Surname;
                    User.Email = p.EmailAddress;
                    AppUsers.AddUsersRow(User);

                }
            }