Sunday, May 20, 2007

Programatically create a SharePoint site based on a site definition

Here is a peice of code that I know you will find useful one day. Basically, you supply it with an existing site definition, say "STS#1", and this will then create a site for you, based on the supplied site definition, at the URL you asked for.

Here goes -

public static bool CreateSite(
string parentSiteURL, string siteURLRequested,
string siteTitle, string siteTemplateName)
{
bool returnCondition = false; // Assume failure.

const Int32 LOCALE_ID_ENGLISH = 1033;

using (SPSite siteCollection = new SPSite(parentSiteURL))
{
SPWeb parentWeb = siteCollection.OpenWeb();
SPWebTemplateCollection Templates =
siteCollection.GetWebTemplates(
Convert.ToUInt32(LOCALE_ID_ENGLISH));
SPWebTemplate siteTemplate = Templates[siteTemplateName];
if (parentWeb.Webs[siteURLRequested].Exists)
{
parentWeb.Webs.Delete(siteURLRequested);
}

parentWeb.Webs.Add(
siteURLRequested,
siteTitle,
"",
Convert.ToUInt32(LOCALE_ID_ENGLISH),
siteTemplate,
false, false);

// All is good?
returnCondition =
true;
}

return returnCondition;
}