Skip to content

Instantly share code, notes, and snippets.

@vman
Last active March 13, 2024 08:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vman/9342224 to your computer and use it in GitHub Desktop.
Save vman/9342224 to your computer and use it in GitHub Desktop.
Create Site Collection from CSOM
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;
using System;
using System.Security;
namespace CreateSiteCollections
{
class Program
{
static void Main(string[] args)
{
//Open the Tenant Administration Context with the Tenant Admin Url
using (ClientContext tenantContext = new ClientContext("https://yoursite-admin.sharepoint.com/"))
{
//Authenticate with a Tenant Administrator
SecureString passWord = new SecureString();
foreach (char c in "password".ToCharArray()) passWord.AppendChar(c);
tenantContext.Credentials = new SharePointOnlineCredentials("admin@yoursite.onmicrosoft.com", passWord);
var tenant = new Tenant(tenantContext);
//Properties of the New SiteCollection
var siteCreationProperties = new SiteCreationProperties();
//New SiteCollection Url
siteCreationProperties.Url = "https://yoursite.sharepoint.com/sites/codesite";
//Title of the Root Site
siteCreationProperties.Title = "Site Created from Code";
//Login name of Owner
siteCreationProperties.Owner = "admin@yoursite.onmicrosoft.com";
//Template of the Root Site. Using Team Site for now.
siteCreationProperties.Template = "STS#0";
//Storage Limit in MB
siteCreationProperties.StorageMaximumLevel = 100;
//UserCode Resource Points Allowed
siteCreationProperties.UserCodeMaximumLevel = 50;
//Create the SiteCollection
SpoOperation spo = tenant.CreateSite(siteCreationProperties);
tenantContext.Load(tenant);
//We will need the IsComplete property to check if the provisioning of the Site Collection is complete.
tenantContext.Load(spo, i => i.IsComplete);
tenantContext.ExecuteQuery();
//Check if provisioning of the SiteCollection is complete.
while (!spo.IsComplete)
{
//Wait for 30 seconds and then try again
System.Threading.Thread.Sleep(30000);
spo.RefreshLoad();
tenantContext.ExecuteQuery();
}
Console.WriteLine("SiteCollection Created.");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment