Thursday, September 11, 2014

Create site collection programmatically in sharepoint 2013 with custom web template

To create site collection programmatically by using server object model use SPWebApplication .Sites.Add method. it has 12 overloads. choose any one which suits you. In this given code I am creating a site collection on host header (not on root site).
References :
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

Code:

 public void CreateSitecollection(string url, string title, string description, string ownerLogin, string ownerName, string ownerEmail, SPWebApplication webApp)
        {
            Uri urlNewSite = new Uri(url);
            try
            {
                if (!SPSite.Exists(urlNewSite))
                {

                    using (SPSite newSiteCollection = webApp.Sites.Add(
                        url,// url of the new site,give full url if you want to create site on host header else"/sites/anyname"
                       title,// title of the new site
                       description,//description
                       1053,//LCID
                       "WT_CollaborationSite",//give custom template naem
                       ownerLogin,// login anme like "corp\devuser"
                       ownerName,// name
                       ownerEmail,// email id of the primary user
                       ownerLogin, // secondry user
                       "",
                       "",
                       true))// user host header
                    {
                     
                    }
                }
                else
                {
                    throw new ArgumentNullException("Site already exists");
                }
            }
            catch (Exception)
            {
             
            }
        }


use this code anywhere like in a timer job or in a console application. give the "STS#0" in the template name if you want to use team site template.