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...


Guest Author: Geeshan01 Dec 2012

You should not dispose SPWeb object here as you are getting it from current context.

Guest Author: AnisBk20 Jun 2013

Nice it works in the Wonderland of Alice, except an error in line 3, :{

" SPSite site = SPContext.Current.Site; "

the error in 'SPContext.Current' it returns NULL.

Help, help my boss gonna execute us all, ALL...

Guest Author: 20 Jun 2013

It works fine in the wonderland of Alice, except an error in line 3 :{

" SPSite site = SPContext.Current.Site; "

" SPContext.Current " returns NULL.

Help, help my boss gonna execute us all, ALL.

-- Regards John F Kennedy from his Grade.

Guest Author: 20 Jun 2013

Thanks for no responding

and the wise man said:

"just replace your code in another method", like :

public void FormEvents_Loading(Object sender,LoadingEventArgs e) {//your code}

it works... and then, go back to your home with a big smile, like you did save the world :}

Regards Superman

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: