title: Get members of an Active Directory group recursively, i.e. including subgroups
body: <p>Given a group like this in Active Directory:</p>
  
  <pre><code>MainGroup
    GroupA
      User1
      User2
    GroupB
      User3
    User4
  </code></pre>
  
  <p>I can easily determine if User3 is member of MainGroup or any of its subgroups with code like this:</p>
  
  <pre><code>using System;
  using System.DirectoryServices;
  
  static class Program {
      static void Main() {
          DirectoryEntry user = new DirectoryEntry("LDAP://CN=User3,DC=X,DC=y");
          string filter = "(memberOf:1.2.840.113556.1.4.1941:=CN=MainGroup,DC=X,DC=y)";
          DirectorySearcher searcher = new DirectorySearcher(user, filter);
          searcher.SearchScope = SearchScope.Subtree;
          var r = searcher.FindOne();
          bool isMember = (r != null);
      }
  }
  </code></pre>
  
  <p>I would like to know if there is a similar way to get all the users that are member of a group or any of its subgroups, i.e. in the example for MainGroup get User1, User2, User3 and User4.</p>
  
  <p>The obvious way of getting all the users is to recursively query each subgroup, but I was wondering if there is an easier way to do it. </p>
  
  <p>Using the same approach with the <code>memberOf:1.2.840.113556.1.4.1941:</code> filter, but using the domain root instead of the user as a search base is not feasible, as the query takes too long (probably it computes all the group memberships recursively for all users in the domain and checks if they are member of the given group).</p>
  
  <p>Which is the best way to get all members of a group, including its subgroups?     </p>