Tuesday, December 8, 2009

Add Permission Level To SharePoint User Group



In this post I'm going to discuss how you can add a permission level (Read, Contribute, Full Control, etc) to a SharePoint user group. Here is a sample code,
        public void addPermissionToGroup()
        {
            SPSite site = new SPSite("http://mysite:5050/");
            SPWeb spWeb = site.OpenWeb();
            string permissionName = "Read";
            string groupName = "Project Manager";

            try
            {
                spWeb.AllowUnsafeUpdates = true;
                SPRoleAssignment roleAssignment = new SPRoleAssignment(spWeb.SiteGroups[groupName]);
                roleAssignment.RoleDefinitionBindings.Add(spWeb.RoleDefinitions[permissionName]);

                if (!spWeb.HasUniqueRoleAssignments)
                    spWeb.BreakRoleInheritance(false);

                spWeb.RoleAssignments.Add(roleAssignment);
                spWeb.Update();
            }
            catch (Exception _exception)
            {
                throw _exception;
            }
            finally
            {
                spWeb.AllowUnsafeUpdates = false;
            }
        }
You can view RoleDefinitions defined for your site by visiting to Site Settings --> Advanced Permissions.

2 comments:

  1. it works great for Administrator logon. Does't work for Readers group. I tried with RunWithElevatedPrivileges, but no luck. Any idea?

    ReplyDelete
  2. @ Anonymous
    The reason is what ever role we are assigning it should have manage permissions feature. Contribute, readers ,viewers doesn't have that feature. So it wont work for them

    ReplyDelete