1

I have a code in which I have to check if a user is a part of a certain group (lets say "GroupA").

I have the user details stored in the Sharepoint variable SPUser. Now I need to check if this user is a part of GroupA and then take some action.

How can I achieve this?

leppie
  • 115,091
  • 17
  • 196
  • 297
user1534235
  • 161
  • 3
  • 16

1 Answers1

1

Source : How to check if a user exists in a group

you can use following extension method, like this:

public static bool InGroup(this SPUser User, string GroupName)
{
    return User.Groups.Cast<SPGroup>().Any(g => g.Name.ToLower() == GroupName.ToLower());
}

Then call it like this:

bool inGroup = spuser.InGroup("GroupName");

If you want to check the current user then another approach can be like this:
From: Check user already exist in specified SharePoint Group

SPWeb web = SPContext.Current.Web;
SPGroupCollection webGroups = web.Groups;

foreach (SPGroup group in webGroups)
{
 //Checking the group
 if (group.ContainsCurrentUser)
 {
  // perform action
 }
 else
 {
  //perform action
 }
}

For More Reference:

Tell if user exists in SharePoint Group through web service

Community
  • 1
  • 1
Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75
  • That is a great approach! I am facing 1 small problem, even though a user is a part of the group I specify here, the condition is not evaluating to true. I have tried using g.Name.Equals("Group Name", StringComparison.OrdinalIgnoreCase) as well. – user1534235 Sep 27 '12 at 13:20