How to get groups included in an ActiveDirectory group using C #?

As mentioned in the header, I need a way to get all the groups in which the group is a member of ActiveDirectory.

To get all the groups in which the user is a 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 you try

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, the group is a member of the row

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

throws an exception:

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

Does anyone know which way to get all groups in which a group is a member?

+3
source share
2 answers

I think I have this on my own:

To get all the groups of which you are a member, you can use

directoryEntry.Properties["memberOf"][0]

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

AD-Object, , , .

+4

, , , :

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());
}
+2

Source: https://habr.com/ru/post/1709189/


All Articles