User Tools

Site Tools


Groups in SharePoint

Obtain an SPGroup from an SPWeb 'web':

// Method #1
SPGroup group = web.SiteGroups.GetByName("GroupName");
// Method #2
SPGroup group = web.SiteGroups.GetByID(groupId); // groupId is an int

Add an SPGroup to a 'web':

// 'groupOwner' is an instance of SPUser.
web.SiteGroups.Add("GroupName", groupOwner, null, "Group description");

Obtain an SPGroup by its name:

SPGroup group = web.SiteGroups["GroupName"];

Add users to an SPGroup:

// 'userNames' is a list of strings representing user names.
// 'web' is an instance of SPWeb.
// 'group' is an instance of SPGroup.
foreach (string name in userNames)
    SPUser user = web.EnsureUser(name); // it may throw an exception "The specified user could not be found"

Remove an SPUser from an SPGroup:

// 'group' is an instance of SPGroup.
// 'user' is an instance of SPUser.

Associate an SPGroup with a web. This way the group will be listed in the People and Group page even if the group does not have access to the web. More info can be found here.

// 'group' is an instance of SPGroup.

Apply permissions to a folder 'MyFolder':

SPFolder folder = lib.RootFolder.SubFolders["MyFolder"];
// Obtain a group which permissions we want to modify for MyFolder.
SPGroup group = web.SiteGroups.GetByID(groupId);
// Instantiate a built-in permission level Editor.
SPRoleDefinition rol = web.RoleDefinitions.GetByType(SPRoleType.Editor);
// Create a role assigment for the gprup.
SPRoleAssignment ass = new SPRoleAssignment(group);
// Add the permission level to the role assignment.
// Break the role inheritance of the destFolder.
// Apply the new role assignment to the folder.

Change group permissions for a folder to read-only:

// 'web' is an SPWeb
// 'groupId' is a GUID of a group
// 'lib' is an SPDocumentLibrary where the folder is located
// 'folderUrlName' is the name of the folder that is part of URL
// Obtain a group by a groupId.
SPGroup group = web.SiteGroups.GetByID(groupId);
// Obtain a folder which permissions we want to change.
SPFolder folder = lib.RootFolder.SubFolders[folderUrlName];
SPRoleAssignmentCollection assignments = folder.Item.RoleAssignments;
SPRoleDefinition rol = web.RoleDefinitions.GetByType(SPRoleType.Reader);
SPRoleAssignment assignment = new SPRoleAssignment(group);
notes/sharepoint2010/spgroup.txt · Last modified: 2020/08/26 (external edit)