title: How to get nested groups (subgroups) in System.DirectoryServices.Protocol in c#
body: <p>I have a function which gets parameter as <code>Distringuished name</code> of a group and returns the nested groups or groups within a given group using <code>SearchRequest</code> query and <code>SearchResponse</code>. The code works fine when I use <code>DirectoryEntry</code> but failed when I use <code>LdapConnection</code> class. It is necessary to work with <code>LdapConnection</code> class. Please find below the code snippet: </p>
  
  <pre><code>public static void GetNestedGroups(string strGroupDN)
  {
      var _currentDomainofLoggedinUser = Domain.GetComputerDomain();
  
      var currentDomainofLoggedinUser = Domain.GetComputerDomain();
      var currentDomainController = currentDomainofLoggedinUser.FindDomainController(); //Gets the current Domain controller
  
      var domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
      string strPath = "LDAP://" + currentDomainController.Name; //Gets the current domain controller name
      AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
      using (LdapConnection ldap = new LdapConnection(new LdapDirectoryIdentifier(domainName, 636)))
      {
          ldap.AuthType = AuthType.Basic;
          ldap.SessionOptions.SecureSocketLayer = false;
          var s = new SecureString();
          NetworkCredential network = new NetworkCredential(WindowsIdentity.GetCurrent().Name, s);
  
          string ldapSearchFilter = String.Format
                ("(&amp;(memberOf={0})(objectClass=group))", strGroupDN);
          NetworkCredential cred = CredentialCache.DefaultNetworkCredentials;
          ldap.Bind(network);
          string[] attributesToReturn = new string[] { "distinguishedName" };
  
  
          SearchRequest searchRequest = new SearchRequest(strGroupDN, ldapSearchFilter, SearchScope.OneLevel, attributesToReturn);
          searchRequest.DistinguishedName =
              strGroupDN;
  
  
          searchRequest.Filter = String.Format
                 ("(&amp;(memberOf={0})(objectClass=group))", strGroupDN);
          SearchResponse response = (SearchResponse)ldap.SendRequest(searchRequest);
          if (response != null &amp;&amp; response.Entries.Count &gt; 0)
          {
              SearchResultEntry obj = response.Entries[0];
  
              var groupCount = ((System.Collections.CollectionBase)(obj.Attributes["memberOf"])).Count;
              foreach (SearchResultEntry entry in response.Entries)
              {
                  var groupName = entry.DistinguishedName;
                  _subGroupList.Add(groupName.ToString().Split('=')[1].Split(',')[0]);
                  GetNestedGroups(groupName);
              }
  
          }
      }
  }
  </code></pre>
  
  <p>In the response it doesn't give anything. (In case of <code>DirectoryEntry</code>, it does provide the result)</p>