title: How can I get the group memberships for an AD user - including all groups in other domains?
body: <p>I have tried the below LDAP search, but it only gives me the group membership for the domain the user is in. I need the search to also include the memberships of the groups that are ForeignSecurityPrincipals (groups on a domain in another AD forest).</p>
  
  <pre><code>public static List&lt;string&gt; GetGroups() 
  { 
    List&lt;string&gt; oGroups = new List&lt;string&gt;(); 
    string vLDAPPath = "GC://dc1.dom1.local/dc=dom1,dc=local"; 
    string vFilterUser = string.Format("(&amp;(objectcategory=user)(objectsid={0}))", "S-1-5-21-122767939-1938435020-1261837966-8097"); 
  
    DirectoryEntry oDirEntry = new DirectoryEntry(); 
    oDirEntry.Path = vLDAPPath; 
    oDirEntry.Username = "dom1\\sysuser"; 
    oDirEntry.Password = "syspwd"; 
  
    DirectorySearcher oDirSearchUser = new DirectorySearcher(); 
    oDirSearchUser.SearchRoot = oDirEntry; 
    oDirSearchUser.Filter = vFilterUser; 
  
    SearchResult oSearchResultUser = oDirSearchUser.FindOne(); 
    if (oSearchResultUser != null) 
    { 
      using (DirectoryEntry oResultDirEntryUser = oSearchResultUser.GetDirectoryEntry()) 
      { 
        oResultDirEntryUser.RefreshCache(new string[] { "TokenGroups" }); 
        PropertyValueCollection tg = oResultDirEntryUser.Properties["TokenGroups"]; 
        foreach (byte[] SID in (Array)tg.Value) 
        { 
          string vFilterGroup = string.Format("(&amp;(objectcategory=group)(objectsid={0}))", SIDToString(SID)); 
          DirectorySearcher oDirSearchGroup = new DirectorySearcher(); 
          oDirSearchGroup.SearchRoot = oDirEntry; 
          oDirSearchGroup.Filter = vFilterGroup; 
          SearchResult oSearchResultGroup = oDirSearchGroup.FindOne(); 
          if (oSearchResultGroup != null) 
          { 
            using (DirectoryEntry oResultDirEntryGroup = oSearchResultGroup.GetDirectoryEntry()) 
            { 
              oGroups.Add(oResultDirEntryGroup.Name); 
            } 
          } 
        } 
      } 
    } 
    return oGroups; 
  }
  </code></pre>