Responsive Ads Here

Thursday, February 6, 2014

How to get the Current User's Group Names in SharePoint

In my current project I have a requirement where I need to show all the group names of current logged in user in a drop down if the group count greater than zero other wise i need to show in label. So i written a method like which is mentioned below it will return a list.
public List GetGroupName()    
{    
  List groupNames = new List();    
  try    
  {    
     SPUserToken saUserToken = SPContext.Current.Site.SystemAccount.UserToken;    
     using (SPSite osite = new SPSite(SPContext.Current.Web.Url, saUserToken))    
     {   
        using (SPWeb oweb = osite.OpenWeb())    
        {    
          SPUser userName = oweb.EnsureUser(SPContext.Current.Web.CurrentUser.LoginName           ); 
       SPGroupCollection collGroups = userName.Groups;   
          if (collGroups.Count > 0)    
          {    
             foreach (SPGroup ogroup in collGroups)    
             {    
                groupNames.Add(ogroup.Name);   
             }    
             return groupNames;    
          }    
          else   
          {    
            return null;   
          }   
       }    
     }    
 }   
 catch (Exception ex)   
 {    
     ex.Message;    
     throw ex;   
 }   
}   

No comments:

Post a Comment