Create a List based on a Template (.stp)

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:

 1: /// <summary>
 2: /// Uploads site Templates
 3: /// </summary>
 4: /// <param name="templateGallery"></param>
 5: /// <param name="templateFiles"></param>
 6: private void UploadTemplates(SPDocumentLibrary
templateGallery,
string[] templateFiles)
 7: {
 8:  if (templateGallery
!= null)
 9:  {
 10:  foreach (string template in templateFiles)
 11:  {
 12:  System.IO.FileInfo fileInfo = new System.IO.FileInfo
(template);
 13:  SPQuery query = new SPQuery();
 14:  query.Query = string.Format("<Where><Eq><FieldRef 
Name='FileLeafRef'/>" +

15: "<Value Type='Text'>{0}</Value></Eq></Where>",

fileInfo.Name);

 16:  SPListItemCollection existingTemplates =
templateGallery.GetItems(query);
 17:  int[] Ids
= new int[existingTemplates.Count];
 18:  for (int i
= 0; i < existingTemplates.Count; i++)
 19:  {
 20:  Ids[i] = existingTemplates[i].ID;
 21:  }
 22:  for (int j
= 0; j < Ids.Length; j++)
 23:  {
 24:  templateGallery.Items.DeleteItemById(Ids[j]);
 25:  }
 26:  byte[] stp = System.IO.File.ReadAllBytes(template);
 27:  templateGallery.RootFolder.Files.Add(fileInfo.Name,
stp);
 28:  }
 29:  }
 30: }

And call that with a:

 

 1:  string directory
= properties.Definition.RootDirectory;
 2: if (!directory.EndsWith(@"\")) 
 3:  directory += @"
\"; directory += "ListTemplates";>
 4:  if (System.IO.Directory.Exists(directory))
 5:  {
 6:  string[] templates = System.IO.Directory.
GetFiles(directory, "
*.stp", System.IO.SearchOption.TopDirectoryOnly);>
 7:  SPDocumentLibrary listTemplates = 

thisWeb.GetCatalog(SPListTemplateType.ListTemplateCatalog) as SPDocumentLibrary;
 8:  UploadTemplates(listTemplates, templates);
 9:  }
 10:  else
 11:  {
 12:  //log error or empty message
 13:  }

>

>

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:

 1: foreach (SPListTemplate
template in thisSite.GetCustomListTemplates
(thisWeb))
 2: {
 3: if (template.Name
== "YourTEmplateName")
 4:  {
 5:  listTemplate = true;
 6:  Guid processGuid = subWeb.Lists.Add("ListName", "ListDescription",
template);
 7:  SPList processlist = subWeb.Lists[processGuid];
 8: 
 9:  processlist.Update();
 10:  subWeb.Update();
 11:  }
 12: }

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

Leave a Reply