Blog Archives

Check if Current User is member of SharePoint Group’s – Programmatically c#

In SharePoint, we have the 3 predetermined permission groups:

  • Visitors
  • Members
  • Owners

You can see this permissions grpups in the /_layouts/permsetup.aspx page.

(Site settings->People and Groups->Settings->Setup groups)

There are properties on the SPWeb class:

  • SPWeb.AssociatedVisitorGroup
  • SPWeb.AssociatedMemberGroup
  • SPWeb.AssociatedOwnerGroup

Programmatically you can check if current user are in one of those Groups, using the following code:

bool isVisitor = false;
bool isMember = false;
bool isOwner = false;

SPWeb web = SPControl.GetContextWeb(System.Web.HttpContext.Current);
            
SPContext currentContext = SPContext.Current;
                  
if (currentContext != null && currentContext.Web.CurrentUser != null)
{
   SPGroupCollection webGroups = web.CurrentUser.Groups;
   if (webGroups != null && webGroups.Count > 0)
   {
       foreach (SPGroup group in web.Groups)
       {
         if (group.ToString() == web.AssociatedVisitorGroup.ToString())
         {
            isVisitor = web.IsCurrentUserMemberOfGroup(group.ID);
         }
         if (group.ToString() == web.AssociatedMemberGroup.ToString())
         {
            isMember = web.IsCurrentUserMemberOfGroup(group.ID);
         }
          if (group.ToString() == web.AssociatedOwnerGroup.ToString())
         {
            isOwner = web.IsCurrentUserMemberOfGroup(group.ID);
         }
       }
   }
if(isVisitor == true)
{
 // User is Visitor
}
if(isMember == true)
{
  // User is Member
}
if(isOwner == true)
{
  // User is Owner
}
Advertisements