Manage SharePoint SPSite Programmatically
SharePoint allows you to manage site creation programmatically. This method of generating sites has several advantages. For instance, you may follow certain standards in naming sites or creating sites with standard features across multiple sites within site collection. You may also want to have one specific account to be assigned to all of the newly created sites. For example, administrator account should be able to access all of the sites and this account should be part of any newly created sites.
The SharePoint SPSite class represents a collection of SharePoint SPWeb objects and don’t get this confused with the site you will create at the later stage. .
SharePoint site creation done programmatically relies on the same principles as command execution for the site creation: STSADM -O CREATESITE command
First thing that you need to do in order to start creating SharePoint site is to add assembly references to your project: There are two assemblies available to you: Microsoft.SharePoint library and Microsoft.SharePoint.Administration library.
Creation of the SharePoint sites requires sufficient privileges to be give to the process that creates sites or user account who runs SPSite creation scripts. It is advisable to use members of the Microsoft.SharePoint.Administration group while creating/managing SharePoint sites programmatically.
In addition, while createing new SPSitpe object you should always call Dispose() method then creation of the site has been completed. This ensures that there are not discarded copies left in the memory. It is also associated with the “memory leak” term. It is important to do so explicitly because SPSite is a wrapper and not handled by garbage collection of the .NET Framework.
using Microsoft.SharePoint; using Microsoft.SharePoint.Administration; using System; class CreateSite { static void Main(string[] args) { if ((args.Length == 0)) { args = new string[7]; args = GetParams(ref args); } AddSPSiteCollection(args); } private static bool AddSPSiteCollection(string[] args) { try { string[] arrSitePath = args[0].Split('/'); string strServerPath = (arrSitePath[0] + ("//" + arrSitePath[2])); SPSite site = new SPSite(strServerPath); SPSiteCollection siteCollection = site.WebApplication.Sites; siteCollection.Add(args[0], args[1], args[2], 1033, args[3], args[4], args[5], args[6]); Console.WriteLine(("SPSite \'" + (args[0] + "\' created."))); site.Dispose(); return true; } catch (Exception ex) { Console.WriteLine(ex.Message); return false; } } }