Get the main group identifier

Trying to get all the groups the user belongs to, INCLUDING the main group:

Doing something like this:

DirectoryEntry entry = new DirectoryEntry(LDAP:/domainXYZ, userx, passwordx); 
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = String.Format("(&(objectClass=user)(userPrincipalName={0}{1}))", userY, LDAP://domainXYZ);
SearchResultCollection resultColln= searcher.FindOne();

string actualGroupName =string.empty;
string grp ="";
foreach (SearchResult singleRes in resultColln)
{
   foreach (object value in singleRes.Properties["memberof"])
   {
       grp = value.ToString();
       Console.WriteLine("group:{0} ", grp);
   }
}

This gives me all the groups except the main group. Is there a way to get the main group name using primaryGroupIDin addition to other groups?

+3
source share
1 answer

You must start another search using the following search filter

string.Format("(&(objectCategory=group)(objectClass=group)(primaryGroupToken={0}))", singleRes.Properties["primaryGroupID"]);

primaryGroupTokenis a computed attribute that is automatically created by Active Directory when a group is created. primaryGroupIDassigned to the user saves this value.

, , UserPrincipal.GetGroups . , .NET 3.5 .

using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
{
    using (UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "YourUser"))
    {
        foreach (Principal p in user.GetGroups())
        {
             Console.WriteLine(p.Name);
        }
    }
 }

GetGroups , , . , GetAuthorizationGroups.

+1

All Articles