title: Get all the user's groups from active directory in C#
body: <p>I'm trying to get all the user's groups in the active directory with c# code.</p>
  
  <p>This is my code:</p>
  
  <pre><code>private List&lt;GroupPrincipal&gt; GetGroups()
  {
      string userName = User.Identity.Name;
      string host = Request.Url.Host.ToLower();
      List&lt;GroupPrincipal&gt; result = new List&lt;GroupPrincipal&gt;();
  
      UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, host), IdentityType.SamAccountName, userName);
      foreach (GroupPrincipal group in user.GetGroups())
      {
          result.Add(group);
      }
      return result;
  }
  </code></pre>
  
  <p>I receive an error on the row that starts with UserPrincipal user that says that the server could not be connected. I'm running my code from the server itself so I can connect it.</p>
  
  <p>What am i doing wrong?</p>
  
  <p>Thank you in advance!</p>