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.
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. ?