Sharepoint: Check if a user is member of a group

Flo picture Flo · Jun 30, 2009 · Viewed 52.2k times · Source

how can I check if a user (not the one currently logged in) is member of a certain group? Trying to retrieve a user from a group of which he's not a member leads to an SPException, so checking for null is not possible.

So how would you solve this problem. At the moment I think about searching in the SPGroup.Users.XML string for the user's name or iterating over all the group members and checking the login names.

Update: I forgot to mention that I want to avoid the usage of exception handling to check the user's membership.

Answer

Anatoly Mironov picture Anatoly Mironov · Dec 1, 2011

Create an Extension class for SPUser and static method:

public static class SPUserExtension {
   public static bool InGroup(this SPUser user, SPGroup group)
      {
        return user.Groups.Cast<SPGroup>()
          .Any(g => g.ID == group.ID);
      }
   }
}

Then invoke this method on your SPUser object:

SPUser user;
SPGroup group;
//...
bool isMember = user.InGroup(group);