开发者

How can I list all SPUser objects in a SPGroup?

开发者 https://www.devze.com 2023-01-11 19:48 出处:网络
I need to retrieve all SPUser\'s from a SPGroup. Unfortunately, the group may contain Active Directory groups, so a simple SPG开发者_开发技巧roup.Users is not enough (I\'d just get a single SPUser for

I need to retrieve all SPUser's from a SPGroup. Unfortunately, the group may contain Active Directory groups, so a simple SPG开发者_开发技巧roup.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?


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.


Unfortunately, it may be the case that not every member of the AD group has a corresponding SPUser object in the site (yet).

In this scenario, I'd enumerate all the members of the active directory group, and force them into the site with the SPWeb's EnsureUser() method, which returns an SPUser, and creates a new one if it doesn't already exist in the site.

For guidance on enumerating active directory members, see Get List of Users From Active Directory In A Given AD Group.

0

精彩评论

暂无评论...
验证码 换一张
取 消