SharePoint: How To Create a SharePoint Permission Group and Add Users Programmatically

Using C# and SharePoint Object Model I will show you how to add a user to an existing or newly created SharePoint Permission Group.

I was working on a project that requires a domain user to be added to the site’s visitors group automatically base on events, and my project is developed in Microsoft Visual Studio so I need write some code to achieve this.

Below is an example code snippet that will show you how to to use SiteGroups.Add() to create a new SharePoint Group and assign the Read permission level by using RoleDefinitionBindings.Add(), add a default user and a group owner:

using (var spSite = new SPSite("SiteURL"))
{
	using (var web = spSite.OpenWeb())
	{
		var groupName = "Group Name";
		var groupDescription = "Group Description";
		var groupOwner = "contoso\\\jbloggs";
		var defaultUser = "contoso\\\jdoe";
		
		
		web.SiteGroups.Add(groupName, groupOwner, defaultUser, groupDescription);
		
		var group = web.SiteGroups[groupName];
		var spRoleAssignment = new SPRoleAssignment(group);
		var permissionName = "Read";
		
		spRoleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions[permissionName]);
		web.RoleAssignments.Add(spRoleAssignment);

		web.Update();
	}
}

(more…)

Shares