Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to get the list of groups that a user is a member of

0.00/5 (No votes)
1 Apr 2003 1  
How to get list of groups user is member of using DirectoryServices in an Active Directory tree.

Introduction

In the previous article, How to get members of a group using DirectoryServices we showed how you can get list of members in a group. In this article we will show you the other way i.e. how to get list of groups that a user belongs to. There is no direct call in DirectoryServices namepsace that will get this accomplished. You can use DirectorySearcher class to get the user object. And then call Invoke method to call Groups method defined in ADSI.

Code Listing

private void Page_Load(object sender, System.EventArgs e)
{
    StringCollection groups = this.GetUserGroupMembership("foo");
    foreach (string gp in groups)
    {
        Response.Write("<br><b>" + gp + "</b>");
    }
}

private StringCollection GetUserGroupMembership(string strUser)
{
    StringCollection groups = new StringCollection();
    try
    {
        DirectoryEntry obEntry = new DirectoryEntry(
            "LDAP://CN=users,DC=pardesifashions,DC=com");
        DirectorySearcher srch = new DirectorySearcher(obEntry, 
            "(sAMAccountName=" + strUser + ")");
        SearchResult res = srch.FindOne();
        if (null != res)
        {
            DirectoryEntry obUser = new DirectoryEntry(res.Path);
            // Invoke Groups method.

            object obGroups = obUser.Invoke("Groups");
            foreach (object ob in (IEnumerable)obGroups)
            {
                // Create object for each group.

                DirectoryEntry obGpEntry = new DirectoryEntry(ob);
                groups.Add(obGpEntry.Name);
            }
        }
    }
    catch (Exception ex)
    {
        Trace.Write(ex.Message);
    }
    return groups;
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here