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.
精彩评论