Sharepoint - Programmatically create Site using Custom Web Template in Sharepoint 2010

Here is how to do it with a custom 2010 Sharepoint WebTemaple definition:

<?xml version="1.0" encoding="utf-8"?>
  <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
   <WebTemplate
    Name="CustomWebTemplate"
    BaseTemplateName="STS"
    BaseTemplateID="1"
    BaseConfigurationID="0"
    Title="Custom Site Template Title"
    Description=""
    DisplayCategory="Custom Template" />
  </Elements>

First find custom templates "Title"

private static String GetTemplate(string solutionName, SPSite siteCollection)
    {
        string templateName = null;
        SPWebTemplateCollection coll = siteCollection.GetWebTemplates(1033);

        foreach (SPWebTemplate template in coll)
        {
            if (template.Title.Equals("Custom Site Template Title", StringComparison.CurrentCultureIgnoreCase))
            {
                templateName = template.Name;
            }
        }

        return templateName;
    }

Then create site:

  private static void AddSite(SPWeb parentSite, string name, string templateName)
    {
        //Create the new site from the template
        bool allowUnsafeupdates = parentSite.AllowUnsafeUpdates;
        parentSite.AllowUnsafeUpdates = true;

        SPWeb newSite = parentSite.Webs.Add(name, name, name, 1033, templateName, false, false);
        newSite.Update();

        parentSite.AllowUnsafeUpdates = allowUnsafeupdates;
    }

Thanks for the post. But using the method GetTemplate(string solutionName, SPSite siteCollection) above was able to get the Template Name, but since in my SPWebTemplateCollection collection, I have multiple site templates with the same "Title". so using the "Title" does not return me the correct site template I need. For example, I have the site template called "hosts" first, then I removed it, recreate a new site template called it with the title "hosts" again. So my problem is, when the new site was created, it was using the old "hosts" template instead of the new one, any one can help me?

string templateFromMethod = GetTemplate("hosts", siteInUserContext);

SPWeb newSubWeb = subsites.Add(TextBox1.Text, TextBox1.Text, TextBox1.Text, 1033, templateFromMethod, false, false);

private static String GetTemplate(string solutionName, SPSite siteCollection) 
        { 
            string templateName = null; 
            //SPWebTemplateCollection coll = siteCollection.GetWebTemplates(1033); 
            SPWebTemplateCollection coll = siteCollection.GetCustomWebTemplates(1033); 
            foreach (SPWebTemplate template in coll) 
            {

                if (template.Title.Equals(solutionName, StringComparison.CurrentCultureIgnoreCase))
                {
                    templateName = template.Name;
                } 
            } 
            return templateName; 
        } 

Tags: