How to check whether a SharePoint user is in a particular group

Here’s a quick function I wrote to check whether a user is a member of a particular SharePoint group:

private bool IsMemberOf(string groupName)
{
    SPUser user = SPContext.Current.Web.CurrentUser;

    try
    {
        if (user.Groups[groupName] != null)
            return true;
        else
            return false;
    }
    catch
    {
        return false;
    }
}

The try-catch is required as – somewhat counter-intuitively – SharePoint seems to throw a “Group not found” error if the user is not a member of the group.

If you enjoyed this post, please share it!

    One comment on “How to check whether a SharePoint user is in a particular group

    1. Bilel EL OMRANI says:

      I found that the curretnUser object does not contain a group, so I think that we should do it with different way.

      private bool IsMemberOf(string groupName)
      {
      SPUser user = SPContext.Current.Web.CurrentUser;
      SPGroup group = SPContext.Current.Web.Groups[groupName];

      return group.Users.GetCollection(new string[] { user.LoginName }).Count > 0;

      }

      Can you Validate this code ?
      Another question, is always currentuser objec have not a groups collection when we get it from the current Context. ?

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>