Create SharePoint List from Custom Template using CSOM

In this post, I am going write C# code sample to create a new list based on existing list template (.stp uploaded to the list template gallery) with managed Client Object Model. Along with creating new sharepoint list or document library, this process creates new content type, site columns , list view and contents (files or list items) if exists in custom list template.

This process includes following steps:

1. Initialize site context by giving site url where we want to create list or document library.
2. Get all custom list templates.
3. Initialize ListCreationInformation with new list or document library name and custom list template.
4. Finally, creates new list with custom template.

private static void CreateLibraryUsingCustomTemplate() 
{ 
    using (var context = new ClientContext("https://spo-tenant.sharepoint.com/sites/teamsite")) 
    { 
        context.Credentials = new SharePointOnlineCredentials("username", securePwd); 
        // Load the custom templates from site collection 
        ListTemplateCollection templates = context.Site.GetCustomListTemplates(context.Web); 
        context.Load(templates); 
        context.ExecuteQuery(); 
        // Initialize list or library creation info 
        var listCreationInfo = new ListCreationInformation 
        { 
            Title = "Test Custom Library", 
            Description = "Test Custom Library" 
        }; 
  
        ListTemplate listTemplate = templates.First(listTemp => listTemp.Name == "<template name>"); 

        listCreationInfo.ListTemplate = listTemplate; 
        listCreationInfo.TemplateFeatureId = listTemplate.FeatureId; 
        listCreationInfo.TemplateType = listTemplate.ListTemplateTypeKind;  
        // Add Document Library to site 
        context.Web.Lists.Add(listCreationInfo); 
        context.ExecuteQuery(); 
    } 
} 

Advertisement

2 thoughts on “Create SharePoint List from Custom Template using CSOM”

  1. Appears this only works for SharePoint online. It appears that the listcreationinformation class for SharePoint 2013 and 2010 don't have the listtemplate property. 🙁

    Reply

Leave a Comment