views:

1561

answers:

2

As the title mentions I need a way to get all groups a group is member of in ActiveDirectory.

To get all groups a user is member of I use

public static DirectoryEntry[] GetGroupsUserIsMemberOf(DirectoryEntry directoryEntry)
{
    ArrayList        groupsUserIsMemberOf = new ArrayList();
    object           groups               = null;
    DirectoryEntry[] userGroupEntries     = null;

    if (directoryEntry != null && directoryEntry.SchemaClassName == "user") {
        groups = directoryEntry.Invoke("Groups", null);

        foreach (object group in (IEnumerable)groups) {
            groupsUserIsMemberOf.Add(new DirectoryEntry(group));
        }

        userGroupEntries = (DirectoryEntry[])groupsUserIsMemberOf.ToArray(typeof(DirectoryEntry));
    }

    return userGroupEntries;
}

but when trying

public static DirectoryEntry[] GetGroupsGroupIsMemberOf(DirectoryEntry directoyEntry)
{
    ArrayList        groupsGroupIsMemberOf = new ArrayList();
    object           groups               = null;
    DirectoryEntry[] groupEntry       = null;

    if (directoyEntry != null && directoyEntry.SchemaClassName == "group") {
        groups = directoyEntry.Invoke("Groups", null); // throws exception (see below)

        foreach (object group in (IEnumerable)groups) {
            groupsGroupIsMemberOf.Add(new DirectoryEntry(group));
        }

        groupEntry = (DirectoryEntry[])groupsGroupIsMemberOf.ToArray(typeof(DirectoryEntry));
    }

    return groupEntry;
}

to get all groups a group is member of the line

        groups = directoyEntry.Invoke("Groups", null); // throws exception (see below)

throws an exception:

"Unknown name. (exception HRESULT: 0x80020006 (DISP_E_UNKNOWNNAME))"

Does someone know a performant way to get all groups a group is member of?

+3  A: 

Think I've got it on my own:

To get all groups a group is member of you can use

directoryEntry.Properties["memberOf"][0]

and you get a string object with all ADObjects your group is member of.

Split it into single AD-Object strings, check if group und you got it.

Inno
Yup, that's the way to do it!
marc_s
+1  A: 

This code will get you a list of groups from the current logged on user, it is faster than querying the domain controller for the information because it comes out of the cached security identifer:

WindowsIdentity currentIdent = WindowsIdentity.GetCurrent();
IdentityReferenceCollection currentGroups = currentIdent.Groups;

List<String> groups = new List<string>();
foreach (IdentityReference indentity in currentGroups)
{
   groups.Add(indentity.Translate(typeof(NTAccount)).ToString());
}
benPearce
Thanks ben, I will give it a try. Regards.
Inno