Requirement: To get SharePoint groups added to the specific web site/subsite level. Assumption is that the subsite is not inheriting permissions.
Solution:
private static List<string> GetAllWebGroups(string webUrl)
{
List<string> lstGroups = new List<string>();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPSite site = new SPSite(webUrl))
{
using (SPWeb spWeb = site.OpenWeb())
{
foreach (SPRoleAssignment roleAssignment in spWeb.RoleAssignments)
{
if (roleAssignment.Member is SPGroup)
{
foreach (SPRoleDefinition roleDefinition in roleAssignment.RoleDefinitionBindings)
{
// To get groups with specific role .
// SPRoleType.Editor does not work for SharePoint 2010
/*The following condition will not return custom roles, remove this condition in case you want to display all groups.*/
if (roleDefinition.Type == SPRoleType.Reader ||
roleDefinition.Type == SPRoleType.Contributor ||
roleDefinition.Type == SPRoleType.WebDesigner ||
roleDefinition.Type == SPRoleType.Administrator)
{
if (!lstGroups.Exists(delegate(string sGroupName) { return sGroupName == roleAssignment.Member.Name; }))
lstGroups.Add(roleAssignment.Member.Name);
}
}
}
}
}
}
});
}
Solution:
private static List<string> GetAllWebGroups(string webUrl)
{
List<string> lstGroups = new List<string>();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPSite site = new SPSite(webUrl))
{
using (SPWeb spWeb = site.OpenWeb())
{
foreach (SPRoleAssignment roleAssignment in spWeb.RoleAssignments)
{
if (roleAssignment.Member is SPGroup)
{
foreach (SPRoleDefinition roleDefinition in roleAssignment.RoleDefinitionBindings)
{
// To get groups with specific role .
// SPRoleType.Editor does not work for SharePoint 2010
/*The following condition will not return custom roles, remove this condition in case you want to display all groups.*/
if (roleDefinition.Type == SPRoleType.Reader ||
roleDefinition.Type == SPRoleType.Contributor ||
roleDefinition.Type == SPRoleType.WebDesigner ||
roleDefinition.Type == SPRoleType.Administrator)
{
if (!lstGroups.Exists(delegate(string sGroupName) { return sGroupName == roleAssignment.Member.Name; }))
lstGroups.Add(roleAssignment.Member.Name);
}
}
}
}
}
}
});
}