Programmatically Set List or Document Library Permissions in SharePoint

Here’s how to programmatically limit the permissions on a list or document library in a SharePoint site:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/// <summary>
/// Set specific list permissions on a site list or document library
/// </summary>
/// <param name="site">Site that contains the list or document library you want to set specific permissions for</param>
/// <param name="listName">Name of the list that you want to set specific permissions on (e.g. "Commercial Documents")</param>
/// <param name="roleNames">Names of the roles that you want to grant permissions to</param>
private void SetListPermissions(SPWeb site, string listName, List<string> roleNames)
{
    SPList siteList = site.Lists[listName];
    siteList.BreakRoleInheritance(true);
    // Remove any roles that are not in list 
    for (int i = siteList.RoleAssignments.Count - 1; i >= 0; i--)
    {
        if (roleNames.IndexOf(siteList.RoleAssignments[i].Member.Name) == -1)
            siteList.RoleAssignments.Remove(i);
    }            
    siteList.Update();
}

and this is an example of how you may call this function:

1
2
3
4
5
6
7
8
9
10
11
using (SPSite siteCollection = new SPSite(siteCollectionUrl))
{
    using (SPWeb parentWeb = siteCollection.OpenWeb())
    {
            SPWeb site = parentWeb.Webs["MySiteName"];
            // Set site permissions
            List<string> principals = new List<string>(new string[] { "My Intranet Owners", "My Management Team", "System Account" });
            SetListPermissions(site, "Commercial Documents", principals);
        }
    }
}

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

6 Comments »

 
  • Mulk Raj says:

    Hi Colin

    Thank you very much for posting this code; still finding my way around SharePoint object model so I have a couple of questions:

    (1) the variable “principals” does this represent Groups of users?
    (2) can the parameter listName be a document library name?
    (3) can the roleName parameter be a Group?

    I’ve not had an opportunity to use the code yet, but it looks like what I’m trying to achieve.

    Many thanks,
    Mulk

  • Colin Millar says:

    Hi Mulk,

    1. Yes – this is an array of group names.
    2. Yes – this is the name of a document library (“Shared Documents” or whatever).
    3. Yes.

    Cheers,

    Colin

  • Nipesh Shah says:

    Nice and Helpful code.

  • Nik says:

    Hey great post, helped me out a lot!

  • Marcus says:

    Hi friend ! And what i need to do to limit the usergroups to see the hole list and not only the list items ? My user group can’t see my list never !

    Thanks !

  • joe says:

    Cool, thanks. Helpful.

 

Leave a Reply

You must be logged in to post a comment.