Get all users from SharePoint group including active directory group V2


Hello everyone,

Some time ago, I wrote about how to retrieve the list of all users of a SharePoint group, including the list of Active Directory users if an AD group was present.

The proposed solution does not appeal to me because the LDAP binding was HardCoded.

I told you about the SPPrincipalInfo class and I had used the method “SPUtility.GetPrincipalsInGroup“.

But I had underestimated this function!

I didn’t thought to pass the Active Directory group name! Indeed, this function works on SharePoint groups but also on AD groups!

So just check if the group is an active directory group with one of the following functions


If(SPUser.IsDomainGroup)


if(SPPrincipalInfo.PrincipalType == SPPrincipalType.SecurityGroup)

If this is the case just make a GetPrincipalsInGroup passing the loginname of the active directory group for a list of users!

No need the LDAP query!

Here is the full code!



DataTable dtuser = new DataTable();

dtuser.Columns.Add("Group User");

SPGroup groupToDisplay = SPContext.Current.Web.SiteGroups.GetByID(DisplayingGroup);

foreach (SPUser user in groupToDisplay.Users)

{

if (user.IsDomainGroup)

dtuser = GetUsers(user.LoginName, dtuser);

else

dtuser.Rows.Add(user.LoginName);

}




DataTable GetUsers(string userLoginName, DataTable dtuser)

{

bool reachedMaxCount;

SPPrincipalInfo[] adUsers = SPUtility.GetPrincipalsInGroup(SPContext.Current.Web, userLoginName, int.MaxValue - 1, out reachedMaxCount) ;

if (adUsers != null && adUsers.Length > 0)

{

foreach (SPPrincipalInfo principal in adUsers)

{

if (principal.PrincipalType == SPPrincipalType.SecurityGroup)

dtuser = GetUsers(principal.LoginName, dtuser);

else

dtuser.Rows.Add(principal.LoginName);

}

}

return dtuser;

}

Hope this helps!

Christopher.

Advertisements

One thought on “Get all users from SharePoint group including active directory group V2

  1. Pingback: Get a list of all SharePoint group’s users including active directory group | Christopher Clement's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s