title: Get all groups for a user using LDAP
body: <p>I've tried to load all groups for a user from LDAP.</p>
  
  <p>Currently I'm testing on our local AD. With the following code I can load all groups of the given user:</p>
  
  <pre><code>public IEnumerable&lt;String&gt; GetUserGroups( String userName )
  { 
      using ( var domainContext = new PrincipalContext( ContextType.Domain, Name ) )
      {
          var user = UserPrincipal.FindByIdentity( domainContext, userName );
          return user.GetAuthorizationGroups().Select( x =&gt; x.Name} ).ToList();
      }
  }
  </code></pre>
  
  <p>But I fail to get the same result using LDAP.</p>
  
  <p>Code using LDAP:</p>
  
  <pre><code>public IEnumerable&lt;String&gt; GetUserGroups1(String userName)
  {
      //returns the container name of the given user
      var containerName = GetUserContainerName(userName); 
      var groups = new List&lt;String&gt;();
      if (containerName == null)
          return groups;
  
      var entry = new DirectoryEntry(String.Format("LDAP://{0}", "DC=example,DC=com"));
  
      var searcher = new DirectorySearcher(entry)
      {
          Filter = String.Format("(member:{0}:=CN={1},{2},{3})",
                                 "1.2.840.113556.1.4.1941",
                                 containerName, "CN=Users", "DC=example,DC=com"),
          SearchScope = SearchScope.Subtree
      };
  
      var result = searcher.FindAll();
      for (var i = 0; i &lt; result.Count; i++)
      {
          var path = result[i].Path;
          var startIndex = path.IndexOf("CN=", StringComparison.Ordinal) + 3;
          groups.Add(path.Substring(startIndex, path.IndexOf(",", startIndex + 1,
                     StringComparison.Ordinal) - startIndex));
       }
       return groups;
  }
  </code></pre>
  
  <p>How can I get all groups for a user using LDAP?</p>