How to Programmatically Set Permissions on Files/Folders in a SharePoint Document Library

Yep, had to figure this out since I'm still working with SharePoint stuff.  I couldn't find any "HowTo's," code samples, tricks, hints, or anything else really helpful on this.  Just a bunch of other folks attemptint to do the same thing.

 This is one of those things where the answer looks simple and seems like it should have been apparent from the start.  Alas I couldn't see it in the beginning either.

 Here's the magic code:

// get a reference to the folder (this assumes path points to a valid folder)

SPFolder folder = SharePointConfiguration.Site.GetFolder(path);

// get a reference to the Sharepoint group collection

SPGroupCollection spc = SharePointConfiguration.Site.SiteGroups;

// get a reference to the group who’s permissions you want to modify for the folder above

SPGroup group = spc[groupName];

// create a role assignment from the group reference

SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)group);

// break role inheritance for folders/files because they will be having permissions separate from their parent file/folder

folder.Item.BreakRoleInheritance(true);

// update the role assignments for the group by adding the permissionSet “TestPermissionLevel” which is a custom

// permissionset I created manually…you can easily use any of the built-in permission sets

roleAssignment.RoleDefinitionBindings.Add(SharePointConfiguration.Site.RoleDefinitions["Test Permission Level"]);

// apply the new roleassignment to the folder. You can do this at the listitem level if desired (i.e. this could be SPfile.Item…. instead of SPFolder.Item)

folder.Item.RoleAssignments.Add(roleAssignment);

Comments