Create a List based on a Template (.stp)

Create a List based on a Template (.stp) header image

So here you found yourself clicking together a list to let users add items early in your development process, next thing you know the list is too big, and they want it to be deployed on their production servers. Or you want to upload an stp and create a list based on it (in my case; I rather upload and deploy an stp create a list based on that, then create an event receiver that added the items by code).

So I spend some time searching the net and created a FeatureReceiver containing the following code:

/// <summary>
/// Uploads site Templates
/// </summary>
/// <param name="templateGallery"></param>
/// <param name="templateFiles"></param>
private void UploadTemplates(SPDocumentLibrary templateGallery, string[] templateFiles) {
  if (templateGallery != null) {
    foreach(string template in templateFiles) {
      System.IO.FileInfo fileInfo = new System.IO.FileInfo(template);
      SPQuery query = new SPQuery();
      query.Query = string.Format("<Where><Eq><FieldRef Name='FileLeafRef'/>" + "{0}", fileInfo.Name);
      SPListItemCollection existingTemplates = templateGallery.GetItems(query);
      int[] Ids = new int[existingTemplates.Count];
      for (int i = 0; i < existingTemplates.Count; i++) {
        Ids[i] = existingTemplates[i].ID;
      }
      for (int j = 0; j < Ids.Length; j++) {
        templateGallery.Items.DeleteItemById(Ids[j]);
      }
      byte[] stp = System.IO.File.ReadAllBytes(template);
      templateGallery.RootFolder.Files.Add(fileInfo.Name, stp);
    }
  }
}

And call that with a:

string directory = properties.Definition.RootDirectory;
if (!directory.EndsWith(@"\"))
  directory += @"\"; directory += "ListTemplates "
  if (System.IO.Directory.Exists(directory)){
    string[] templates = System.IO.Directory.GetFiles(directory, " * .stp ", System.IO.SearchOption.TopDirectoryOnly)
    SPDocumentLibrary listTemplates = thisWeb.GetCatalog(SPListTemplateType.ListTemplateCatalog) as SPDocumentLibrary;
    UploadTemplates(listTemplates, templates);
  }
  else {
   //log error or empty message
  }

That small piece of code will upload all .stp files to your ListTemplateGallery allowing you to create Lists based on them with the following code:

foreach (SPListTemplate template in thisSite.GetCustomListTemplates(thisWeb)){
  if (template.Name == "YourTEmplateName") {
    listTemplate = true;
    Guid processGuid = subWeb.Lists.Add("ListName", "ListDescription", template);
    SPList processlist = subWeb.Lists[processGuid];

    processlist.Update();
    subWeb.Update();
  }
}

For me it saved me a lot of work, hope it will do the same for you.

Loading comments…