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.
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); } } }
Sorry but there is an error in this script at
ReplyDeleteSPUser spUser = web.EnsureUser("Login Account");
system will return an exception in case on the "Login Account" is not exists;
Okay, i understand it. But it's a validation thing, we do not pass invalid account. It can be validated if required.
Delete