Ads

Wednesday, 15 May 2013

Using C# code to 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("Site URL");
    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 navigating to
Site Settings --> Advanced Permissions.

No comments:

Post a Comment

Ads