Home > SharePoint Development > How to get all Groups for specific user in SharePoint using C#

How to get all Groups for specific user in SharePoint using C#

string user=”Domain\UserName”;
string siteName=”http://server:port”;public Hashtable FindExistingUserGroups(string user, string siteName)
{
Hashtable htAssignGroup = new Hashtable();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteName))
{
try
{
for (int i = 0; i < site.AllWebs.Count; i++)
{
SPWeb web = site.AllWebs[i];
SPUser oUser = web.AllUsers[user];
SPGroupCollection oGroupColl = oUser.Groups;
foreach (SPGroup oGroup in oGroupColl)
{
if (!htAssignGroup.ContainsKey(oGroup.Name)) htAssignGroup.Add(oGroup.Name, oGroup.Name);
}

//Find Group by SPGroup Object
using (SPSite sGroup = new SPSite(siteName, oUser.UserToken))
{
foreach (SPGroup gp in sGroup.OpenWeb().Groups)
{
using (SPWeb web = sGroup.OpenWeb(gp.ParentWeb.ID))
{
SPGroup impersonatedGroup = web.SiteGroups[gp.Name];
if (impersonatedGroup.ContainsCurrentUser)
if (!htAssignGroup.ContainsKey(impersonatedGroup.Name)) htAssignGroup.Add(impersonatedGroup.Name, impersonatedGroup.Name);
}
}
}
}
}
catch (Exception ex)
{
}
}
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return htAssignGroup;
}

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: