title: check if user is a member of a group
body: <p>I have a code to check if the user is a member of a group. 
  I am using this at my login.</p>
  
  <p>Please note I have a domain user and local user eg. <code>testdomain\administrator</code> and <code>administrator</code>.</p>
  
  <p>This is the code I use:</p>
  
  <pre><code>using (DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./" + userGroupName + ",group"))
  {
      foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))
      {
          using (DirectoryEntry memberEntry = new DirectoryEntry(member))
          {
              string completeName = memberEntry.Name;
              DirectoryEntry domainValue = GUIUtility.FindDomain(memberEntry);
              if (domainValue != null)
              {
                  completeName = domainValue.Name + "\\" + memberEntry.Name;
              }
              Global.logger.Info("completeName from " + userGroupName + " = " + completeName);
              if (userName.Equals(completeName, StringComparison.InvariantCultureIgnoreCase))
              {
                  Global.logger.Debug("IsUserPartOfWindowsGroup returned True with username =" + userName + " , UserGroupName = " + userGroupName);
                  return true;
              }
          }
      }
      Global.logger.Debug("IsUserPartOfWindowsGroup returned false for username =" + userName + " , UserGroupName = " + userGroupName);
      return false;
  }
  </code></pre>
  
  <p>This code works, but </p>
  
  <pre><code>DirectoryEntry domainValue = GUIUtility.FindDomain(memberEntry);
  </code></pre>
  
  <p>is taking a lot of time in the profiler as I see it. Is there a better/ faster way to handle this?</p>
  
  <pre><code>public static DirectoryEntry FindDomain(DirectoryEntry memberEntry)
  {
      if (memberEntry.Parent != null)
      {
          if (memberEntry.Parent.SchemaClassName.Equals("domain", StringComparison.InvariantCultureIgnoreCase))
          {
              return memberEntry.Parent;
          }
      }
      return null;
  }
  </code></pre>
  
  <p>another way:</p>
  
  <pre><code>DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userName, Password);
  DirectorySearcher mySearcher = new DirectorySearcher(entry);
  mySearcher.Filter = "(&amp;(objectClass=user)(|(cn=" + userName + ")(sAMAccountName=" + userName + ")))";
  SearchResult result = mySearcher.FindOne();
  
  Global.logger.Info("result == " + result.Path);
  foreach (string GroupPath in result.Properties["memberOf"])
  {
      if (GroupPath.Contains(adminGroupName))
      {
          Global.logger.Info(compUsrNameForEncryption + "exists in " + adminGroupName);
      }
  }
  </code></pre>