Add or Remove permission level to SharePoint group or user programmatically.

  • Posted by: Softree Technology

[code lang=”c”]
Below code describes how to add/remove permission level to user programmatically using client object model.

class Program

{

static void Main(string[] args)

{

using (ClientContext ctx = new ClientContext(“http://siteUrl”))

{

NetworkCredential netCredentials = new NetworkCredential(“userName”, “password”);

ctx.Credentials = netCredentials;

try

{

Web web = null;

web = ctx.Web;

RoleAssignmentCollection assignColl;

RoleAssignment roleAssign;

string userOrGroup = “Administrator”; //we can give either title or login Name of the user/group.

string permissionLevel = “Full Control”; //we can Give name of any permission level name.

ctx.Load(web.RoleAssignments,

roles => roles.Include(

r => r.Member,

r => r.Member.LoginName,

r => r.Member.Title,

r => r.RoleDefinitionBindings

));

ctx.ExecuteQuery();

assignColl = web.RoleAssignments;

for (int isitePermCount = 0; isitePermCount < assignColl.Count; isitePermCount++)

{

try

{

roleAssign = assignColl[isitePermCount];

string userLoginName = string.Empty;

string userTitle = string.Empty;

userLoginName = roleAssign.Member.LoginName;

userTitle = roleAssign.Member.Title;

if (userTitle == userOrGroup || userLoginName == userOrGroup)

{

//Get the roledefinition from it’s name

RoleDefinition roleDef = web.RoleDefinitions.GetByName(permissionLevel);

// If we want to Remove selected Permission

roleAssign.RoleDefinitionBindings.Remove(roleDef);

// If we want to Add selected Permission

roleAssign.RoleDefinitionBindings.Add(roleDef);

roleAssign.Update();

ctx.ExecuteQuery();

Console.WriteLine(“Permission level added successfully”);

}

}

catch { }

}

Console.ReadLine();

}

catch { }

}

}

}
[/code]

Author: Softree Technology

Leave a Reply