sharepointactive-directoryspgroupspuser

How can I list all SPUser objects in a SPGroup?


I need to retrieve all SPUser's from a SPGroup. Unfortunately, the group may contain Active Directory groups, so a simple SPGroup.Users is not enough (I'd just get a single SPUser for the AD group, with the IsDomainGroup property set to true).

Does anyone have a good idea how can I obtain a list of all SPUser's, descending into any Active Directory groups contained in a SPGroup? Is there an alternative to SPGroup.ContainsCurrentUser that takes a SPUser parameter?


Solution

  • Based on a blog post I found, I have written the following code:

    private static List<SPUser> ListUsers(SPWeb web, SPPrincipal group)
    {
        try
        {
            web.Site.CatchAccessDeniedException = false;
            var users = new List<SPUser>();
            foreach(SPUser user in web.SiteUsers)
            {
                using(var userContextSite = new SPSite(web.Site.ID, user.UserToken))
                {
                    try
                    {
                        using (var userContextWeb = userContextSite.OpenWeb(web.ID))
                        {
                            try
                            {
                                if (userContextWeb.SiteGroups[group.Name]
                                    .ContainsCurrentUser)
                                        users.Add(user);
                            }
                            catch (SPException)
                            {
                                // group not found, continue
                            }
                        }
                    }
                    catch(UnauthorizedAccessException)
                    {
                        // user does not have right to open this web, continue
                    }
                }
            }
            return users;
        }
        finally
        {
            web.Site.CatchAccessDeniedException = true;
        }
    }
    

    I don't like the fact that I have to impersonate every single user, and this code will only find AD users that have already been imported into SharePoint (so an SPUser exists for them), but that's good enough for me.