Link to home
Start Free TrialLog in
Avatar of tmitchell68
tmitchell68

asked on

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

Hello,

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>;

objADSearcher.Filter="(&(objectClass=user)(anr="+strLogin+"))";
objADSearcher.PropertiesToLoad.Add("memberOf");
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,
Tim
Avatar of ihenry
ihenry

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.
ASKER CERTIFIED SOLUTION
Avatar of ihenry
ihenry

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tmitchell68

ASKER

Thank you.