How to get groups a group is member of in ActiveDirectory using C#?

3

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?

c#
.net
active-directory
asked on Stack Overflow May 27, 2009 by Inno

2 Answers

4

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.

answered on Stack Overflow May 27, 2009 by Inno
2

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());
}
answered on Stack Overflow Jun 1, 2009 by benPearce

User contributions licensed under CC BY-SA 3.0