Check if user belongs to given SPGroup or not in SharePoint
Hi All,
The following method to check if user belongs to given group in sharepoint. This is very useful utility function when we work on any sharepoint user management activities.
public bool IsUserAuthorized(string groupName)
{
//Retreiving the current context
SPSite site = SPContext.Current.Site;
//Opening a current web and creating a instance
using (SPWeb web = site.OpenWeb())
{
//Retreiving the current logged in user
SPUser currentUser = web.CurrentUser;
//Retrieving all the user groups in the site/web
SPGroupCollection userGroups = currentUser.Groups;
//Loops through the grops and check if the user is part of given group or not.
foreach (SPGroup group in userGroups)
{
//Checking the group
if (group.Name.Contains(groupName))
return true;
}
}
return false;
}
Hope it helps. Happy Coding...
You should not dispose SPWeb object here as you are getting it from current context.