Ads

Tuesday, 7 March 2017

C# code to check user permission in SharePoint list

The following sample shows how to check adding list item permissions for the current user.
using (SPSite spSite = new SPSite("http://MySiteUrl"))
{
  using (SPWeb spWeb = spSite.OpenWeb())
  {
    // Get the current user.
    SPUser currentUser = spWeb .SiteUsers[HttpContext.Current.User.Identity.Name.ToString()];
    // Get the list.
    SPList spList = spWeb.Lists["MyList"];
    // Variable to determine permission.
    bool userPermission = spList.DoesUserHavePermissions(currentUser, SPBasePermissions.AddListItems);
    if ( userPermission )
    {
      // Perform operation here.
    }
  }
}

The local variable "userPermission" will set to True if the user can add items in list otherwise it will set to false.
Similarly,
For viewing list item
   bool userPermission = spList.DoesUserHavePermissions(loginUser, SPBasePermissions.ViewListItems);
For editing list item
   bool userPermission = spList.DoesUserHavePermissions(loginUser, SPBasePermissions.EditListItems);
For deleting list item
   bool userPermission = spList.DoesUserHavePermissions(loginUser, SPBasePermissions.DeleteListItems);

No comments:

Post a Comment

Ads