Using Active Directory to get a System Domain User's groups in C#


I am attempting to use C# code to get the Active Directory groups that a user belongs to.

This is the code I have so far...

DirectoryEntry objRootEntry=new DirectoryEntry("");

DirectorySearcher objADSearcher=new DirectorySearcher(objRootEntry);

string strLogin = <The user's userid>;

SearchResult objResult=objADSearcher.FindOne();

if (objResult != null)
      int groupCount = objResult.Properties["memberOf"].Count;

      for (int counter=0; counter<groupCount; counter++)
          string strGroup = (string)objResult.Properties["memberOf"][counter];

This works fine - as long as the user has a System Account.  If the user has a Domain User Account, I get the following error:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 333:                  if (objResult != null)
Line 334:                  {
Line 335:                        int groupCount = objResult.Properties["memberOf"].Count;
Line 336:
Line 337:                        for (int counter=0; counter<groupCount; counter++)

"memberOf" doesn't seem to exist for Domain Users.

Any help or suggestions would be greatly appreciated.

Thank you in advance,
Who is Participating?
Anyway, to prevent the code from throwing the exception, you can try this

if ( objResult.Properties.Contains("memberOf") )
   for (int counter=0; counter<objResult.Properties["memberOf"].Count; counter++)
As you have already noticed, user object's "memberOf" attribute does not contain "primary group" (e.g. Domain Users group). It also pick up only security groups and distribution groups of which the user is a direct member. So if your active directory contains recursive list of nested group relationship, you won't find them in the attribute.

There's another attribute, "tokenGroups". It returns primary group and all groups membership including nested relationship, but security groups only. So depend on your active directory structure and what you want, this could quite complicated since you might need to use several methods to query group membership.
tmitchell68Author Commented:
Thank you.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.