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(); } }
So in the future if you want to add more users to an existing SharePoint Group, you can use SiteGroups.AddUser(). The example code snippet below gets all the user from the SharePoint site and add them all to the same group:
using (var spSite = new SPSite("SiteURL") { using (var web = spSite.OpenWeb()) { var groupName = "Group Name"; var spUserCollection = web.Users; foreach (SPUser user in spUserCollection) { web.SiteGroups[groupName].AddUser(user); } web.Update(); } }