Today, in our current project, we got one requirement: Get the groups via current logon user.
As you know, i first search the MSDN. I got two objects: SPGroup, SPUser. How should use them.
I create a virtual web part to test them, below is the code, you could use these code to check whether a user belongs to one given SPGroup or not in SharePoint.You will find this is very useful when you work on any user and group manage in sharepoint 2007 and sharepoint 2010
private bool GetGroupofUser()
{
bool flag = false;
using (SPSite siteCollection = SPContext.Current.Site)
{
using (SPWeb site = siteCollection.OpenWeb())
{
string groupName = "TestGroup";
//Get the current logged in user
SPUser currentUser = site.CurrentUser;
//Get all the user groups in the site/web
SPGroupCollection userGroups = currentUser.Groups;
//Loops through the grops and check if the user is part of given group or not.
foreach (SPGroup group in userGroups)
{
//Checking the group
if (group.Name.Contains(groupName))
flag = true;
break;
}
}
}
return flag;
}