How to get all the AD groups for a particular user?

后端 未结 10 1672
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 04:19

I checked this post already. But it doesn\'t answer my question. I want to get all the active directory groups in which a particular user is a member.

I\'ve written

10条回答
  •  鱼传尺愫
    2020-11-28 05:12

    The following example is from the Code Project article, (Almost) Everything In Active Directory via C#:

    // userDn is a Distinguished Name such as:
    // "LDAP://CN=Joe Smith,OU=Sales,OU=domain,OU=com"
    public ArrayList Groups(string userDn, bool recursive)
    {
        ArrayList groupMemberships = new ArrayList();
        return AttributeValuesMultiString("memberOf", userDn,
            groupMemberships, recursive);
    }
    
    public ArrayList AttributeValuesMultiString(string attributeName,
         string objectDn, ArrayList valuesCollection, bool recursive)
    {
        DirectoryEntry ent = new DirectoryEntry(objectDn);
        PropertyValueCollection ValueCollection = ent.Properties[attributeName];
        IEnumerator en = ValueCollection.GetEnumerator();
    
        while (en.MoveNext())
        {
            if (en.Current != null)
            {
                if (!valuesCollection.Contains(en.Current.ToString()))
                {
                    valuesCollection.Add(en.Current.ToString());
                    if (recursive)
                    {
                        AttributeValuesMultiString(attributeName, "LDAP://" +
                        en.Current.ToString(), valuesCollection, true);
                    }
                }
            }
        }
        ent.Close();
        ent.Dispose();
        return valuesCollection;
    }
    

    Just call the Groups method with the Distinguished Name for the user, and pass in the bool flag to indicate if you want to include nested / child groups memberships in your resulting ArrayList:

    ArrayList groups = Groups("LDAP://CN=Joe Smith,OU=Sales,OU=domain,OU=com", true);
    foreach (string groupName in groups)
    {
        Console.WriteLine(groupName);
    }
    

    If you need to do any serious level of Active Directory programming in .NET I highly recommend bookmarking & reviewing the Code Project article I mentioned above.

提交回复
热议问题