Getting the Current User's Group Names in SharePoint

Bhanubysani
Posted by Bhanubysani under SharePoint category on | Points: 40 | Views : 2932
In my current project i have requirement like, 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; //To get the System User Identity
using (SPSite osite = new SPSite(SPContext.Current.Web.Url, saUserToken))
{
using (SPWeb oweb = osite.OpenWeb())
{
SPUser userName = oweb.EnsureUser(SPContext.Current.Web.CurrentUser.LoginName); //Getting the Current User Login Name
SPGroupCollection collGroups = userName.Groups; //Returning the current user group collection
if (collGroups.Count > 0) //Checking the Count of Group collection
{
foreach (SPGroup ogroup in collGroups) //Looping the group collection and adding to the list
{
groupNames.Add(ogroup.Name);
}
return groupNames;
}
else
{
return null;
}
}
}
}
catch (Exception ex)
{
ex.Message;
throw ex;
}
}

Comments or Responses

Login to post response