title: C# Get all groups of specific user from Active Directory
body: <p>I'm trying to get all the groups of a specific user, as it listed in Active Directory "Member Of" groups.
  I found a code but it gives me all of the groups, if a group contains few groups, I get those groups instead of the main one that contains them.. I would like to get the list as it is without "background" groups.</p>
  
  <p>code that i found here:</p>
  
  <pre><code>public List&lt;GroupPrincipal&gt; GetGroups(string userName)
  {
     List&lt;GroupPrincipal&gt; result = new List&lt;GroupPrincipal&gt;();
  
     // establish domain context
     PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);
  
     // find your user
     UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, userName);
  
     // if found - grab its groups
     if(user != null)
     {
        PrincipalSearchResult&lt;Principal&gt; groups = user.GetAuthorizationGroups();
  
        // iterate over all groups
        foreach(Principal p in groups)
        {
           // make sure to add only group principals
           if(p is GroupPrincipal)
           {
               result.Add((GroupPrincipal)p);
           }
        }
     }
  
     return result;
  }
  </code></pre>
  
  <p>Haven't find a working solution yet, any idea?</p>