DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

Check whether User exists in SharePoint Group or not

By Ashok Nalam on 21 May 2013 | Category: Sharepoint | Tagged: .NET groups 
In this snippet we will see how to check whether the user belongs to a SharePoint group or not
  Discuss Add Comment   |  
Add rating Rate this resource  [Rated 5.00/5 by 1 people] 
The snippet covers how to check whether user belongs to a SharePoint group or not.

Code:

//checks user exists in SPGroup
public static bool IsUserExsistsInSPGroup(SPSite site, string groupName, SPUser spUser)
{
            bool userExsists = false;
            //Executes this method with Full Control rights even if the user does not have Full Control
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPWeb spWeb = site.RootWeb)
                {
                        if (CheckGroupExistsInSiteCollection(spWeb, groupName))
                        {
                            SPGroup spGroup = spWeb.Groups[groupName];
                            if (spGroup != null)
                            {
                                userExsists = spUser.Groups.Cast<SPGroup>().Any(g => g.Name.ToLower() == groupName.ToLower());
                            }
                        }
                }
            });
            return userExsists;
}
//checks group exists in site collection
private static bool CheckGroupExistsInSiteCollection(SPWeb web, string groupName)
{
  return web.SiteGroups.OfType<SPGroup>().Count(g => g.Name.Equals(groupName, StringComparison.InvariantCultureIgnoreCase)) > 0;
}
In order to call the method, use the below code

SPSite currentSite = SPContext.Current.Site;
SPUser currentUserName = SPContext.Current.Site.RootWeb.EnsureUser(SPContext.Current.Web.CurrentUser.LoginName);
bool isUserPartofGV = IsUserExsistsInGroup(currentSite,"Group Visitors",currentUserName)

Output:

Returns True/False based on user existence in SharePoint group.

  Discuss Add Comment    
Add rating Rate this resource  [Rated 5.00/5 by 1 people] 
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9526  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.
 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys