|
How to get list of groups user is member of
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.
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;
}
|