Creating a new SharePoint site programmatically

Creating sites through code adds the ability to package them in .wsp files. When developed applications have to be pushed to a production environment, recreating all created sites manually can be a cumbersome task. By using code, we’re able to automate this task.

I created a new Empty SharePoint project and added an event receiver. Next, uncomment both FeatureActivated and FeatureDeactivating code blocks. Open up your code file and add the following variables:

const int LOCALE_ID = 1033;
const string SITE_NAME = "Site";
const string SITE_TITLE = "Site Title";
const string SITE_DESCRIPTION = "This is your new site!";
const string SITE_TEMPLATE = "STS#1";

The variable names are self-explanatory. There’s a complete list available with all the IDs.

The following line will create the new SharePoint site:

SPContext.Current.Web.Webs.Add(SITE_NAME, SITE_TITLE, SITE_DESCRIPTION, LOCALE_ID, oWebTemplate, false, false);

To clean things up a bit and check for validation, I use the following FeatureActivated code block:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPWeb oWeb = SPContext.Current.Web;
    SPWebTemplate oWebTemplate = oWeb.GetAvailableWebTemplates(LOCALE_ID)[SITE_TEMPLATE];
    SPWebCollection cWebs = oWeb.Webs;

    SPWeb tWeb = cWebs[SITE_NAME];
    if (!tWeb.Exists)
    {
        SPWeb xWeb = cWebs.Add(SITE_NAME, SITE_TITLE, SITE_DESCRIPTION, LOCALE_ID, oWebTemplate, false, false);
        xWeb.Dispose();
    }
    tWeb.Dispose();
}

Next, code the FeatureDeactivating block:

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    SPWeb oWeb = SPContext.Current.Web;

    if (oWeb.Webs[SITE_NAME].Exists)
    {
        try
        {
            oWeb.Webs.Delete(SITE_NAME);
        }
        catch (Exception)
        {

            throw;
        }
    }
}

That should do it! Also make sure your feature doesn’t get enabled by default. Double click on the feature file and switch “Activate On Default” to false:

activate feature by default

One thought on “Creating a new SharePoint site programmatically

Leave a comment