Friday, December 13, 2013

Check User exists in SharePoint Group

I was looking for direct API method to check whether specified user exists in SharePoint group. Unfortunately there is no direct API check.

I found below single statement is efficient for this check. I made it a generic for re-usability.

SPGroup spGroup = web.Groups["Group Name"];
if (null != spGroup)
{
  SPUser spUser = web.EnsureUser("Login Account");
  if (null != spUser)
  {
    bool userExsists = spUser.Groups.Cast<SPGroup>().Any(g => g.Name.ToLower() == spGroup.Name.ToLower());
     if (!userExsists)
     {
        spGroup.AddUser(spUser);
     }
  }
}

2 comments:

  1. Sorry but there is an error in this script at
    SPUser spUser = web.EnsureUser("Login Account");
    system will return an exception in case on the "Login Account" is not exists;

    ReplyDelete
    Replies
    1. Okay, i understand it. But it's a validation thing, we do not pass invalid account. It can be validated if required.

      Delete