title: Active Directory Subgroups search
body: <p>I need have a root AD group and need to enumerate through all its subgroups. I have a code, that connects to the AD server and tries to retrieve subgroups list.</p>
  
  <p>Here's the code:</p>
  
  <pre><code>        private IEnumerable&lt;SearchResult&gt; GetSubGroups(string groupId)
          {
              using (var searcher = new DirectorySearcher(new DirectoryEntry(adServerName, adLogin, adPassword)))
              {
  
                  searcher.Filter = string.Format("(&amp;(objectClass=group)({0}))", groupId);
                  //Get the Root Group
                  var result = searcher.FindOne();
                  object resultMembers = result.GetDirectoryEntry().Invoke("Members", null);
  
                  foreach(var member in ((IEnumerable) resultMembers))
                  {
                      var memberEntry = new DirectoryEntry(member);
  
                      var subgroupsSearcher = new DirectorySearcher(memberEntry);
                      subgroupsSearcher.Filter = "(objectClass=group)";
                      subgroupsSearcher.PropertiesToLoad.Add("samaccountname");
                      subgroupsSearcher.PropertiesToLoad.Add("name");
  
                      var foundSubGroupResult = subgroupsSearcher.FindOne();
  
                      ...
                  }
  
                  return new List&lt;SearchResult&gt; {result};
              }
      }
  </code></pre>
  
  <p>When enumerating throught the Invoke("Members", null) results I create another DirectoryEntry for each result.
  The problem is, that when a <code>subgroupSearcher.FindOne()</code> is called, it ends up with a <code>DirectoryServicesCOMException</code>.</p>
  
  <pre><code>Here's the exception stack trace:
  at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
  at System.DirectoryServices.DirectoryEntry.Bind()
  at System.DirectoryServices.DirectoryEntry.get_AdsObject()
  at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
  at System.DirectoryServices.DirectorySearcher.FindOne()
  ...other methods...
  </code></pre>
  
  <p>Exception's Message property says: <code>"An operations error occured"</code>
  I've logged the ErrorCode, it's <code>-2147016672</code></p>
  
  <p>I also attempted to initialize UserName property implicitly, when creating the DirectoryEntry from the subgroup object:</p>
  
  <pre><code>foreach(var member in ((IEnumerable) resultMembers))
                      {
                          var memberEntry = new DirectoryEntry(member);
                          memberEntry.Username = adLogin;
                          var subgroupsSearcher = new DirectorySearcher(memberEntry)
  
                          ...
                      }
  </code></pre>
  
  <p>But it gave the same result.</p>
  
  <p>What I'm doing wrong? Any help is appreciable.</p>