views:

33

answers:

1

Hey I have the following code. I get a directory entry for a user (strpath). And then I get the groups where the user is listed.

How can I get the number of users in each group?

DirectoryEntry myDE = new System.DirectoryServices.DirectoryEntry(strpath);
object obGroups = myDE.Invoke("Groups");
foreach (object ob in (IEnumerable)obGroups)
{
    DirectoryEntry obGpEntry = new DirectoryEntry(ob);
    GroupsListBox.Items.Add(obGpEntry.Name );
}
A: 

If you're on .NET 3.5 (or can upgrade to it), there's a massively extended System.DirectoryServices.AccountManagement namespace that makes these jobs of managing user, groups and their memberships a whole lot easier.

Check out the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 for an introduction to S.DS.AM.

You can get a user principal like this:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");

UserPrincipal user = UserPrincipal.FindByIdentity("some user name");

PrincipalSearchResult<Principal> userGroups = user.GetGroups();

foreach (Principal p in myGroups)
{
    GroupPrincipal gp = (p as GroupPrincipal);

    if (gp != null)
    {
        int memberCount = gp.Members.Count;
    }
}

This way, you can enumerate all groups a given user has, and enumerating those groups, you can find out how many members (users and other groups) each group has.

marc_s