Search code examples
c#active-directorydirectoryservicesdirectoryentryaccount-management

How to search Global Catalog (whole forest) using PrincipalContext


 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);

                }
            }

I have code similar to the above that searches Active Directory for user information using PrincipalContext class.

As you can see i pass in the domainName during the search. How can i modify this peace of code to instead search the entire forest (i.e Global Catalog) but still use the PrincipalContext class?

I can't seem to find a working example that uses PrincipalContext class to do a Global Catalog search.

I have seen this post How to search for users in Global Catalog within AD forest with multiple trees but the poster seems to suggest that they did not find a solution that uses PrincipalContext class, they had to switch back to DirectorySearcher.

Is there any PrincipalContext class code sample that demonstrates searching in the whole forest (Global Catalog)?


Solution

  • ok, i got it working. I just had to change my code like below.

     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);
    
                    }
                }