title: Get members of group nested in another group
body: <p>I'm developing an intranet which shows specific links only if a user is member of certain groups in Active Directory.</p>
  
  <p>I'm using this code to effectively check if a user is member of a group. Works fine if the group contains users only, but it doesn't work if there's a group nested in it. What I need is to make it works even if a particular user is in the nested group!    </p>
  
  <pre><code>public bool isMember(string user, string group)
  {
      string value = "";
      bool isMember = false;
  
      try
      {
          DirectoryEntry entry = new DirectoryEntry(domain);
          DirectorySearcher mySearcher = new DirectorySearcher(entry);
          mySearcher.Filter = "sAMAccountname=" + user;
  
          SearchResult mySearchResult;
  
          mySearchResult = mySearcher.FindOne();
  
          PropertyValueCollection prop = mySearchResult.GetDirectoryEntry().Properties["memberOf"];
  
          for (int i = 0; i &lt; prop.Count; i++)
          {
              value = prop[i].ToString();
  
              string[] groups = value.Split(',');
              foreach (string property in groups)
              {
                  if (groups[1] == group)
                  {
                      isMember = true;
                      break;
                  }
              }
          }
          entry.Close();
          return isMember;
      }
      catch (COMException)
      {
          return false;
      }
  }
  </code></pre>
  
  <p>How can I accomplish this?</p>
  
  <p><strong>EDIT :</strong></p>
  
  <p>I've found this code, which allows me to find a user, even if a nested group. The problem is that it works only if my organizational unit contains ONE group, doesn't work if there are more than one...do you think I can edit it a bit to make it work properly??</p>
  
  <pre><code>public bool isMember(string user, string group)
  {
      bool found = false;
  
      PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain");
      GroupPrincipal p = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, group);
      UserPrincipal u = UserPrincipal.FindByIdentity(ctx, user);
  
      found = p.GetMembers(true).Contains(u);
  
      p.Dispose();
      u.Dispose();
  
      return found;
  }
  </code></pre>
  
  <p>Got this code from -><a href="https://stackoverflow.com/questions/14332964/how-i-can-make-a-recursiv-search-in-ad-with-a-user-whether-this-is-in-a-group-or">here</a>&lt;-</p>