The snippet covers how to check whether user belongs to a SharePoint group or not.Code:
//checks user exists in SPGroup
public static bool IsUserExsistsInSPGroup(SPSite site, string groupName, SPUser spUser)
{
bool userExsists = false;
//Executes this method with Full Control rights even if the user does not have Full Control
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPWeb spWeb = site.RootWeb)
{
if (CheckGroupExistsInSiteCollection(spWeb, groupName))
{
SPGroup spGroup = spWeb.Groups[groupName];
if (spGroup != null)
{
userExsists = spUser.Groups.Cast<SPGroup>().Any(g => g.Name.ToLower() == groupName.ToLower());
}
}
}
});
return userExsists;
}
//checks group exists in site collection
private static bool CheckGroupExistsInSiteCollection(SPWeb web, string groupName)
{
return web.SiteGroups.OfType<SPGroup>().Count(g => g.Name.Equals(groupName, StringComparison.InvariantCultureIgnoreCase)) > 0;
}
In order to
call the method, use the below code
SPSite currentSite = SPContext.Current.Site;
SPUser currentUserName = SPContext.Current.Site.RootWeb.EnsureUser(SPContext.Current.Web.CurrentUser.LoginName);
bool isUserPartofGV = IsUserExsistsInGroup(currentSite,"Group Visitors",currentUserName)
Output:
Returns True/False based on user existence in SharePoint group.