How to: Create or Delete a Site or a Site Collection
Last modified: April 12, 2010
Applies to: SharePoint Foundation 2010
To create a site, use one of the Add() methods of the SPWebCollection class. To create a subsite beneath a site, use the Webs property of the SPWeb class to return the collection of subsites and then call one of the Add() methods for the collection.
The code examples in this topic use members of the Microsoft.SharePoint.SPContext class to obtain the current site collection, Web site, or list. Outside of an HTTP context, such as in a console application or a Windows application, you obtain references to key objects by using a different method. For more information, see Getting References to Sites, Web Applications, and Other Key Objects.
The following example creates a new subsite that is based on the template of the current site and on information gathered from three text boxes. The text boxes specify the name to use in the new URL, the title to use for the site, and a description for the site.
In the example, the WebTemplate property of the SPWeb class returns the name of the current site definition, which is passed as a parameter of the Add method. In addition, three parameters for this method pass the information that is gathered from the three text boxes. The three other parameters specify the following:
LocaleID folder (where LocaleID is the locale identifier (LCID) for the installation; the LCID for English - United States is 1033)
true to create a site with unique permissions, and
false to convert any existing Web site at the same location to a SharePoint site.
SPWeb mySite = SPContext.Current.Web; SPWebCollection subSites = mySite.Webs; string currentTemplate = mySite.WebTemplate; string siteUrl = TextBox1.Text.ToString(); string siteTitle = TextBox2.Text.ToString(); string siteDescription = TextBox3.Text.ToString(); subSites.Add(siteUrl, siteTitle, siteDescription, 1033, currentTemplate, true, false);
string deleteSite = TextBox1.Text.ToString(); SPSite mySite = SPContext.Current.Site; SPWebCollection sites = mySite.AllWebs; sites.Delete(deleteSite);
The previous examples each require a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace.
For information about how to create an application page that works in the context of SharePoint Foundation, see Creating Application Pages for SharePoint.