SharePoint Blogs / SharePoint University
SharePoint Blogs and SharePoint University - all in one place!
Need SharePoint Training? Attend a SharePoint Bootcamp!

Please delete cookies related to sharepointblogs.com and sharepointu.com to resolve login issues!

Saving a custom list template and importing it to another site programmatically.

I decided to write this post after reading a community question on a forum about how can you export and import a list template programmatically. This post will explain how can you save a list template from an existing list and then copy it to a different site (in a different web application). It is fairly a simple process if you are using SharePoint interface. But how can you accomplish this programmatically? Assume the template you want to save is from a list called "MyList"

using (SPWeb web = SPContext.Current.Web)
{
  SPList list = web.Lists["MyList"];
  list.SaveAsTemplate("MyListTemplate.stp", "My List", "My List Desc", true);
  list.Update();
}
                                                                                                                                                                                                        
Once you have the SPList it is pretty straight forward to save the list template. here I am saving the template as MyListTeplate.stp. and giving the template title as "My List". When you run this bit of code and go to "Site Actions->Create" you will see the newly created list template under Libraries section. Or you can check the List Template Gallery by  going to "Site Actions->Site Settings" and clicking on "List templates" under "Galleries" section.

 

 Now how would you import the same list template to another site in a different web application programmatically?

 

when you save the list template you can read the file in to a byte array without actually saving it in to the hard disk and reading it. Get the "List Template Gallery" list into an SPList. This list contains all the list templates for lists in your site. You can read the list template into a byte array using this code.

 

byte[] templateArr = lst.RootFolder.Files["_catalogs/lt/MyListTemplate.stp"].OpenBinary();

Open the site you want to copy this list template and get the "List template gallery" list of that site (http://MySiteB). Below code illustrates this operation. However you will have to make adjustment the code to cater for different security issues depending on your site.                                                                                               

  

using (SPWeb web = SPContext.Current.Web)
{
  SPList lst = web.Lists["List Template Gallery"];
 
   //you can open the template file into a byte array
   byte[] templateArr = lst.RootFolder.Files["_catalogs/lt/MyListTemplate.stp"].OpenBinary();
   SPUser user = web.CurrentUser;
   SPUserToken usrToken = user.UserToken;
   SPSecurity.RunWithElevatedPrivileges(delegate()
     {
       //open the site using existing user credentials.
       using (SPSite site = new SPSite(http://MySiteB, usrToken))
              {
              using (SPWeb web2 = site.RootWeb)
                      {
                       web2.AllowUnsafeUpdates = true;
                      //get the existing liste template list of site B
                      SPList templateList = web2.Lists["List Template Gallery"];
                      try
                         {
                          //add the template file (byte array) to the template list of this site.
                          templateList.RootFolder.Files.Add("_catalogs/lt/MyListTemplate.stp", templateArr, true);
                          templateList.Update();
                        }
                     catch (Exception er)
                        { }
                  }
              }
         });
}
    

 

Now if you go to http://MySiteB and inspect the list template gallery you will see the newly added template. I'd be interested to know your comments and better ways to do this. So looking forward to know your ideas and suggestions.

Sajana Palanagama

Posted 07-06-2008 7:30 PM by Sajana

Comments

Links (7/8/2008) « Steve Pietrek - Everything SharePoint wrote Links (7/8/2008) « Steve Pietrek - Everything SharePoint
on 07-08-2008 6:54 PM

Pingback from  Links (7/8/2008) « Steve Pietrek - Everything SharePoint

Roopa wrote re: Saving a custom list template and importing it to another site programmatically.
on 09-10-2008 5:33 AM

Hi,

good one. it was very useful.

JP wrote re: Saving a custom list template and importing it to another site programmatically.
on 09-23-2008 6:13 PM

After installing the List Template to the "List Template Gallery", how can I create a list from that  programmatically?

I tried using the web.ListTemplates["template Name"]

but I get an index out of range.

Any ideas??

JP wrote re: Saving a custom list template and importing it to another site programmatically.
on 09-30-2008 12:36 PM

I figured it out, any "List Template Gallery" item , is located at the site level not the web. That was my misunderstanding.

Here is the code.

public void CreateListUsingListTemplateGalleryItem(SPWeb web, string strTitle, string strDescription, string strListTemplateGalleryItemName)

       {

                      foreach (SPListTemplate listTemp in web.Site.GetCustomListTemplates(web))

           {

               if (listTemp.Name == strListTemplateGalleryItemName.Replace(".stp", ""))

               {

                   web.AllowUnsafeUpdates = true;

                   web.Lists.Add(strTitle, strDescription, listTemp);

                   web.Update();

                   break;

               }

           }          

       }

Viktor Dolezel wrote re: Saving a custom list template and importing it to another site programmatically.
on 11-07-2008 11:45 AM

Sajana, good post, thanks.

One suggestions though: Don't do the following

using (SPWeb web = SPContext.Current.Web)

{

....

}    

This code may be Disposing SPWeb instance that you have not created.

Sajana wrote re: Saving a custom list template and importing it to another site programmatically.
on 11-10-2008 4:40 PM

Hey Viktor,

Thanks for pointing that out.

Cheers

Vishal wrote re: Saving a custom list template and importing it to another site programmatically.
on 11-17-2008 7:59 AM

Hi,

I am going through this post and it is very useful for me but I am facing some problem in GetCustomListTemplate method.

Here I am not able to find the saved template file, still it is present in my sharepoint site at _catalog/lt.

Can some one please help.

Sajana wrote re: Saving a custom list template and importing it to another site programmatically.
on 11-17-2008 4:59 PM

Hi Vishal,

Make sure your code is looking at the correct web. (SPWeb)

Debug this line "templateList.RootFolder" and see if it is the correct path.

hope this helps

Regards

sajana

Vishal wrote re: Saving a custom list template and importing it to another site programmatically.
on 11-18-2008 4:12 AM

Hi Sajana,

Thanks for reply, I am debuging my code and the SPWeb is also right.

The saved template is present at _catalog\lt folder at site but not coming  collection return by method GetCustomListTemplate().

If we save any SPList as template from sharepoint site it get saved at same location specfied above and magicaly it is coming in collection return by method GetCustomeListTemplate(). but if we same process through the code the collection is empty.

My code is as below

SPSite siteColl = new SPSite(SPContext.Current.Web.Site.ID);

    if (siteColl.RootWeb.GetFile("_catalogs/lt/" + "DecisionTaskTemplate.stp").Exists)

                {

                siteColl.RootWeb.Lists[GlobalResources.Resources.ListTemplateGalleryName].RootFolder.Files[

                                       "DecisionTaskTemplate.stp"].Recycle();

                 }

   SPContext.Current.Web.Lists["Decision Task " + cashedFile.Name.Replace(".aspx","")].SaveAsTemplate("DecisionTaskTemplate.stp","DecisionTaskTemplate", "Template", true);

   SPContext.Current.Web.Lists["Decision Task " + cashedFile.Name.Replace(".aspx", "")].Update(true);

   SPContext.Current.Web.Update();

//For retriving the saved template

SPSite globalSiteColl = new SPSite(SPContext.Current.Web.Site.ID);

     foreach (SPListTemplate listTemplate in globalSiteColl.GetCustomListTemplates(globalSiteColl.RootWeb))

           {

               if (listTemplate.Name.Equals("DecisionTaskTemplate.stp"))

               {

                    SPContext.Current.Web.Lists.Add("Decision Task " + addedFile.Name.Replace(".aspx", ""), "Decision Task " + addedFile.Name.Replace(".aspx", ""), listTemplate);

                }

           }

Siva wrote re: Saving a custom list template and importing it to another site programmatically.
on 12-01-2008 1:41 PM

On what event this method should be called. I am trying to create a feature

How do we call the method on activate feature

Siva wrote re: Saving a custom list template and importing it to another site programmatically.
on 12-01-2008 2:05 PM

I got it I am adding it on Feature activated event.

Peto wrote re: Saving a custom list template and importing it to another site programmatically.
on 02-26-2009 5:58 AM

Hi, thanks for the article and thanks to JP comments,

Finally i found the customtemplates (I was looking at templatelist, not at customlistTemplates), and could create the list programatically, but when using inside a foreach the second list created failed and said:

____________

Excepción no controlada: Microsoft.SharePoint.SPException: Ocurrió una excepción. (Excepción de HRESULT: 0x80020009 (DISP_E_EXCEPTION)) ---> System.Runtime.InteropServices.COMException (0x80020009): Ocurrió una excepción. (Excepción de HRESULT: 0x80020009 (DISP_E_EXCEPTION))

  en Microsoft.SharePoint.Library.SPRequestInternalClass.CreateCustomList(String bstrUrl, String bstrTitle, String strDescription, String bstrCustomTemplateName)

  en Microsoft.SharePoint.Library.a.b(String A_0, String A_1, String A_2, String A_3)

  --- Fin del seguimiento de la pila de la excepción interna ---

  en Microsoft.SharePoint.Library.a.b(String A_0, String A_1, String A_2, Strin

g A_3)

  en Microsoft.SharePoint.SPListCollection.Add(String strTitle, String strDescr

iption, SPListTemplate template)

  en CreaLib.CreaLib.Main(String[] args)

_____________

At last I solved this with a workaround, each iteration I Close the web and open it again...? It Woks!!

_____________

           SPSite site = new SPSite("SitePath");

           SPWeb Web = site.OpenWeb("webpath");

           SPListTemplate MyCustomTemplate= site.GetCustomListTemplates(Web)[TemplateName];

           foreach (item i in MyList)

           {

               try

               {

                   //Create Library from Template

                   Web.Lists.Add(Title, Desc,MyCustomTemplate);

                   Web.Update();

                   Web.Close();

                   Web = site.OpenWeb("webpath");

....

_________________________

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
Need SharePoint Training? Attend a SharePoint Bootcamp!
Posts (c) their respective authors. Everything else (c) 2009 SharePoint Experts, Inc.