How To: Add a permission group in the document library's folders
This is the snippet which will add a permission group in the document library’s folders.
1: using System;
2: using System.Collections.Generic;
3: using System.Text;
4: using Microsoft.SharePoint;
5:
6: namespace ConsoleApplication1
7: {
8: class Program
9: {
10: static void Main(string[] args)
11: {
12: Console.WriteLine("Enter your site URL");
13: string strSiteName = Console.ReadLine();
14:
15: Console.WriteLine("Enter your document library name");
16: string strDocumentLibrary = Console.ReadLine();
17:
18: Console.WriteLine("Enter your group name");
19: string strGroup = Console.ReadLine();
20:
21: Assign(strSiteName, strDocumentLibrary, strGroup);
22:
23: Console.WriteLine("Done!");
24: Console.ReadLine();
25: }
26:
27: public static void Assign(string strSiteName, string strDocumentLibrary, string strGroup)
28: {
29: SPSite WebApp = new SPSite(strSiteName);
30: SPWeb Site = WebApp.OpenWeb();
31: SPList list = Site.Lists[strDocumentLibrary];
32: SPContentTypeCollection oContentTypes = list.ContentTypes;
33: String url = list.RootFolder.ServerRelativeUrl.ToString();
34:
35: foreach (SPListItem folder in list.Folders)
36: {
37: WebApp.AllowUnsafeUpdates = true;
38: Site.AllowUnsafeUpdates = true;
39:
40: SPRoleDefinitionCollection roleDefinitions = Site.RoleDefinitions;
41: SPRoleAssignmentCollection roleAssignments = folder.RoleAssignments;
42:
43: SPGroup grp = Site.Groups[strGroup];
44: SPRoleAssignment roleAssignment = new SPRoleAssignment(grp);
45: SPRoleDefinitionBindingCollection roleDefBindings = roleAssignment.RoleDefinitionBindings;
46:
47: roleDefBindings.Add(roleDefinitions["Contribute"]);
48: roleAssignments.Add(roleAssignment);
49:
50: WebApp.AllowUnsafeUpdates = false;
51: Site.AllowUnsafeUpdates = false;
52: }
53: Site.Close();
54: WebApp.Close();
55: Site.Dispose();
56: WebApp.Dispose();
57: }
58: }
59: }
I have tested this code for a folder “test12” in “RFC” document library. The permission group which I added is “test1”.
Result
KEYWORDS:
====================
Permission inheritance, adding SharePoint group at each folder level in a document library