Reset Unique Permissions (Reset Broken Inheritance) In SharePoint using CSOM – C#

Sometimes we may require to delete unique permissions and reset broken inheritance (recover inheritance) for a particular site, or list library, or list item. In this post, I am going to write C# code to reset stopped role inheritance using CSOM (Client Object Model).

Reset Role Inheritance of a Site

The following C# code reset the broken inheritance of a sharepoint site.

private static void ResetRoleInheritanceInSite()
{
    string sitrUrl = "https://sptenant.sharepoint.com/sites/contosobeta/sbeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        var site = ctx.Web;
        //Stop Inheritance from parent site
        site.ResetRoleInheritance();
        ctx.Load(site);
        ctx.ExecuteQuery();
    }
}

Reset Broken Inheritance of a List Library

The following C# code reset the broken inheritance of a sharepoint list library.

private static void ResetRoleInheritanceInList()
{
    string sitrUrl = "https://sptenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        var web = ctx.Web;
        ctx.Load(ctx.Web, a => a.Lists);
        ctx.ExecuteQuery();

        List list = ctx.Web.Lists.GetByTitle("TestDocLibrary");
        //Stop Inheritance from parent
        list.ResetRoleInheritance();
        list.Update();
        ctx.ExecuteQuery();
    }
}

Reset Unique Permissions for a List Item

The following C# code reset the broken inheritance for a sharepoint list document item.

private static void ResetRoleInheritanceInListItem()
{
    string sitrUrl = "https://sptenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        var web = ctx.Web;
        ctx.Load(ctx.Web, a => a.Lists);
        ctx.ExecuteQuery();                

        List list = ctx.Web.Lists.GetByTitle("TestDocLibrary");
        string document = "TestFile.txt";
        CamlQuery camlQuery = new CamlQuery();
        camlQuery.ViewXml = "" + document + "";

        var items = list.GetItems(camlQuery);
        ctx.Load(items);
        ctx.ExecuteQuery();
        foreach (var item in items)
        {
            item.ResetRoleInheritance();
            ctx.ExecuteQuery();
        }
    }
}

Advertisement

Leave a Comment