How to create a site or subsite in SharePoint Online?

This article will show you how to create a site or Sub Site in SharePoint. In the same way we can create a site or subsite using SharePoint Online/2013/2016/2019. Also, we will check the below things:

  • How to create a site in SharePoint Online or SharePoint 2013/2016/2019
  • How to create a subsite in SharePoint 2013 Online programmatically using CSOM
  • SharePoint Check if subsite exists using CSOM
  • How to Create subsite in SharePoint Online programmatically
  • Create subsite in SharePoint programmatically using server object model
  • Create subsite in SharePoint programmatically using csom (client side object model)
  • How to delete sites and subsites programmatically using CSOM in SharePoint Online
  • How to Get all subsites from a site collection in SharePoint Online using CSOM
  • Get all subsites from a site collection in SharePoint using CSOM
  • Get Subsites of a SharePoint Online Site Collection using PowerShell

Before I explain about subsites, I would like to share a few ideas about the hierarchy of SharePoint (On-premises). Please look into the below screenshot.

But in SharePoint Online, We are not creating any farm or web application, directly we are creating site collections.

create site in sharepoint
create site in sharepoint

You can create multiple numbers of subsites under a Site collection in SharePoint. The web application is the parent of the Farm in SharePoint.

Site Collection is the child of the Web Application in SharePoint and the subweb is like a grandchild of the site collection in SharePoint.

There is no difference between a Site collection and subsites; only the hierarchy is different. You can create multiple numbers of subsites under a site collection in SharePoint. You can inherit the permission from the parent site collection to child subsites. Below, I have listed a few mandatory fields to create a site collection in SharePoint.

  1. Title
  2. Description
  3. URL
  4. TemplateType
  5. Permission

A company has multiple branches in different countries and states. So, we have to create an application in SharePoint which will manage all different sites for a different country.

Suppose My company name is: RajInfotech and it’s located in the USA, CANADA, INDIA, DUBAI. So here, I have to create a Web Application for RajInoftech and Rajinfotech is the parent and we have to create all branches under Rajinfotech main website.

Web Application Name (Company Name)

URL : http:// Rajinfotech.com (Web Application Name)

Site collection (Country Name)

URL : http:// Rajinfotech.com/Sites/INDIA

SubSites (States)

In a country, If we have multiple branch then we have to create a Sub site under a site collection like

URL : http:// Rajinfotech.com/Sites/INDIA/Bangalore

[Video Tutorial] Create a Subsite in SharePoint Online

Below, I have listed a few mandatory fields to create a site collection in SharePoint.

  1. Title
  2. Description
  3. URL
  4. TemplateType
  5. Permission

You can open this video for your better understanding.

Subscribe to EnjoySharePoint YouTube Channel for more SharePoint video tutorials.

This SharePoint video tutorial explains, how to create a subsite in SharePoint Online Office 365.

Create site in SharePoint Online or SharePoint 2013/2016/2019

Step 1 :On your SharePoint site navigate to the Settings gear icon and click ‘Add an app’

create site in sharepoint 2013
create site in sharepoint

Step 2 : Next, click on Subsites .

create site in sharepoint 2016
create site in sharepoint 2013

Step 3: Click on New SubSite button in top of the page.

create site in sharepoint 2019
create site in sharepoint 2013

Step 4: Enter your Site Title and description and select Team site as default template and Use same permissions as parent site and click on Create button.

How to create site in SharePoint 2013
create site in sharepoint

Step 5: Once you click on Create, It will take a moment to create a new team site for you. Below screenshot is the new subsite which is created recently.

How to create site in SharePoint 2013
How to create site in SharePoint 2013

This is all about creating a site or subsite in SharePoint. I will explain more about site features in my next article.

Create subsite in SharePoint 2013 Online programmatically using CSOM

Now, I will explain how to create a subsite in SharePoint 2013 Online programmatically using CSOM under a current web site. Here we will use the WebCreationInformation class to create a new website.

Before we start, we need to create a console application in Visual Studio. Here I am using Visual Studio 2010 but you can do the same thing in a higher version of Visual Studio.

Create subsite in SharePoint 2013 Online programmatically using CSOM

Now, we will see how we can create a subsite under a site collection programmatically using CSOM in SharePoint Online.

Step 1: Open your Visual Studio

Step 2: Create a new console application and enter your solution Name and save it in your any drive location.

Create subsite in SharePoint 2013 Online programmatically using CSOM
Create subsite in SharePoint 2013 Online programmatically using CSOM

Step 3: Before we start , we need to add the SharePoint client object model dll in our application. For adding the dll we can add the dll manually under references or we can download it from NuGet gallery.

Step 4: For download the dll from NuGet , we have to go the manage NuGet packages under Tool in Visual Studio.

sharepoint create subsite programmatically
sharepoint create subsite programmatically

Step 5: Download the references which is required to connect SharePoint online. Below is the screenshot of reference file which is required to download.

sharepoint online create subsite programmatically
sharepoint online create subsite programmatically

Step 6: Next click on Install button. Once it will done, we will get an screen to select the project.

create subsite sharepoint 2013 c#
create subsite sharepoint 2013 c#

Step 7: Once you click on OK button , again you will get an screen to click Accept or Decline. Please click on Accept button to go forward.

create subsite sharepoint 2013 c#
create subsite sharepoint 2013 c#

Step 8: Once you click on Accept button, Download will start and you will get your all references inside reference file in your application.

sharepoint create subsite programmatically
sharepoint create subsite programmatically

Step 9: Next open your Program.cs file and write the below code under Main function.

using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;

namespace createListusingCSOM
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "[email protected]";
            Console.WriteLine("Enter Your Password Please  ------- ");
            SecureString password = GetPasswordOfYourSite();
            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();

            using (var clientContext = new
            ClientContext("https://pikasha12.sharepoint.com/sites/DLH")) 
                {
                // SharePoint Online Credentials  
                clientContext.Credentials = new SharePointOnlineCredentials(userName, password);
                // Get the SharePoint web  
                WebCreationInformation creation = new WebCreationInformation();
                creation.Url = "MyConsoleWeb";
                creation.Title = "WelcomeToConsoleWeb";
                Web newWeb = clientContext.Web.Webs.Add(creation);

                // Retrieve the new web information. 
                clientContext.Load(newWeb, w => w.Title);
                clientContext.ExecuteQuery();
                clientContext.ExecuteQuery();
            }

        }

        private static SecureString GetPasswordOfYourSite()
        {
            ConsoleKeyInfo info;
            //Get the user's password as a SecureString  
            SecureString securePassword = new SecureString();
            do
            {
                info = Console.ReadKey(true);
                if (info.Key != ConsoleKey.Enter)
                {
                    securePassword.AppendChar(info.KeyChar);
                }
            }
            while (info.Key != ConsoleKey.Enter);
            return securePassword;
        }
    }
}

Step 10 : Test the application:

Hit F5 to run the application. Enter the password and then click on Enter button.

create subsite in sharepoint 2013 programmatically csom
create subsite in sharepoint 2013 programmatically csom

This is how to create a subsite in SharePoint 2013/2016/Online programmatically using CSOM (Client object model).

SharePoint Check if subsite exists using CSOM

This SharePoint tutorial explains, how to check if subsite exists using csom. We will use .Net managed client object model (csom) in SharePoint Online to check if subsite exists sharepoint c#.

Here we will create a console application to do the demo on the check is subsite exists sharepoint csom.

Check is subsite exists SharePoint csom

Now, we will write our csom code to check if the subsite exists in SharePoint Online using c#.

Open visual studio and then click on File -> New -> Project…

And then choose Choose Visual C# -> Windows and then choose Console Application from the list of templates.

Now we can add Microsoft.SharePoint.Client.dll from NuGet Package.

Then go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution…

And then search for Microsoft.sharepoint.client and then select Microsoft.SharePoint.Client.Online.CSOM and then click on Install button like below:

check if subsite exists sharepoint c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using System.Security;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
bool isExists;
var password = new SecureString();
foreach (char c in "*********".ToCharArray()) password.AppendChar(c);
var credentials = new SharePointOnlineCredentials("******@OnlySharePoint2013.onmicrosoft.com", password);

using (ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"))
{
context.Credentials = credentials;
var web = context.Web;
context.Load(web, w => w.Webs);
context.ExecuteQuery();
var subWeb = (from w in web.Webs where w.Url == "https://onlysharepoint2013.sharepoint.com/sites/Bhawana/MySubSite" select w).SingleOrDefault();
if (subWeb != null)
{
isExists = true;
}
else
{
isExists = false;
}
}
}
}
}

The above code will return true if the SharePoint subsite exists else it will return false.

This is how to check if subsite exists in SharePoint using CSOM.

Create subsite in SharePoint Online programmatically

This SharePoint tutorial explains, how to create a SharePoint subsite programmatically using the server object model and client object model in SharePoint 2013/2016.

Also, we will see how to delete a SharePoint subsite programmatically using the SharePoint client object model (CSOM).

I have used a windows application to create subsites in SharePoint 2016. But the same code will work for SharePoint 2013.

Create subsite in SharePoint programmatically using server object model

Below is the code to create a subsite using SharePoint 2016 server object model.

using (SPSite site = new SPSite("http://mypc:29024/sites/SPTraining/"))
{
using (SPWeb newWeb = site.OpenWeb())
{
newWeb.AllowUnsafeUpdates = true;
SPWebCollection subsites = newWeb.Webs;
SPWeb newSubWeb = subsites.Add("MySiteFromServerObjectModel", "My Site from Server Object Model", "This is a site from server object model.", 1033, "STS#0", true, false);
newWeb.Update();
}
}

Create subsite in SharePoint programmatically using csom (client side object model)

Below is the csom code to create a subsite programmatically using csom in SharePoint 2013/2016.

using (ClientContext ctx = new ClientContext("http://mypc:29024/sites/SPTraining/"))
{
WebCreationInformation websitecreationinfo = new WebCreationInformation();
websitecreationinfo.Url = "MySiteFromClientObjectModel";
websitecreationinfo.Title = "My Site from Client Object Model";
websitecreationinfo.Description = "This is a site from client object model.";
websitecreationinfo.UseSamePermissionsAsParentSite = true;
websitecreationinfo.WebTemplate = "STS#0";
websitecreationinfo.Language = 1033;
Web w = ctx.Site.RootWeb.Webs.Add(websitecreationinfo);
ctx.ExecuteQuery();
}
Create subsite in SharePoint programmatically

Delete sites and subsites programmatically using CSOM in SharePoint Online

Let us see how to delete all sites, subsites programmatically using csom in SharePoint Online.

Here I am testing it using a windows application, you can also do it using a console application to connect to SharePoint Online sites.

To work with SharePoint objects using csom, we need to add the below dlls.

  • Microsoft.SharePoint.Client
  • Microsoft.SharePoint.Client.Runtime

Delete sites and subsites programmatically using CSOM in SharePoint

Below is the full code to delete sites and subsites programmatically from a SharePoint site collection using csom in SharePoint Online.

private void button3_Click(object sender, EventArgs e)
{
using (ClientContext context = new ClientContext(“https://<tenantname>.sharepoint.com/sites/Bhawana/”))
{
string username = ” **********@<tenantname>.onmicrosoft.com”;
context.AuthenticationMode = ClientAuthenticationMode.Default;
var secureString = new SecureString();
foreach (char c in ” **********”)
{
secureString.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials(username, secureString);
try
{
DeleteSites(context, username, secureString);
}
catch (Exception ex)
{
throw;
}
}
}

public void DeleteSites(ClientContext context, string username, SecureString password)
{
Hashtable hsSites = getAllSites(context, context.Url.ToString(), username, password);
foreach (DictionaryEntry item in hsSites)
{
Hashtable hsSubsites = getSubWebs((Web)item.Key, item.Value.ToString(), username, password);
foreach (DictionaryEntry item1 in hsSubsites)
{
ClientContext ct = new ClientContext(item1.Value.ToString());
ct.AuthenticationMode = ClientAuthenticationMode.Default;
ct.Credentials = new SharePointOnlineCredentials(username, password);
Web web1 = ct.Web;
web1.DeleteObject();
ct.ExecuteQuery();
}
ClientContext ctSite = new ClientContext(item.Value.ToString());
ctSite.AuthenticationMode = ClientAuthenticationMode.Default;
ctSite.Credentials = new SharePointOnlineCredentials(username, password);
Web web = ctSite.Web;
web.DeleteObject();
ctSite.ExecuteQuery();
}
}
public Hashtable getAllSites(ClientContext clientContext, string url, string username, SecureString password)
{
Hashtable hsSites = new Hashtable();
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(username, password);
var Web = clientContext.Web;
clientContext.Load(Web, w => w.Webs);
clientContext.ExecuteQuery();
foreach (Web orWebsite in Web.Webs)
{
hsSites.Add(orWebsite, orWebsite.Url);
}
return hsSites;
}

public Hashtable getSubWebs(Web Website, string siteUrl, string username, SecureString password)
{
Hashtable hsSubSites = new Hashtable();
try
{
ClientContext clientContext = new ClientContext(siteUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(username, password);
Web oWebsite = clientContext.Web;
clientContext.Load(oWebsite, website => website.Webs, website => website.Title);
clientContext.ExecuteQuery();
foreach (Web orWebsite in oWebsite.Webs)
{
hsSubSites.Add(orWebsite, orWebsite.Url);
getSubWebs(orWebsite, orWebsite.Url, username, password);
}
}
catch (Exception ex)
{
}
return hsSubSites;
}

By using the above code, we can delete all SharePoint sites and subsite programmatically.

Here, we saw, how to create a subsite programmatically in SharePoint using server object model or client object model (CSOM). Also, we learned how to delete a subsite or site in SharePoint programmatically.

Get all subsites from a site collection in SharePoint Online using CSOM

Now, let us check, how to get all subsites from a site collection in SharePoint Online using .net managed object model (csom). Also, we will see how to get all subsites under a site collection using PowerShell in SharePoint Online Office 365.

We will see how to retrieve all sites excluding the apps or add-in websites from a SharePoint Online site using.Net managed code in SharePoint Online.

Here I will create a console application to run the csom code and we will connect to the SharePoint Online sites.

Get all subsites from a site collection in SharePoint using CSOM

Whenever you will try to retrieve all the subsites of a site collection in SharePoint programmatically using .Net managed object model (csom) code, it will return all the subsites as well as it will return all the apps or add-in websites if you have deployed any SharePoint hosted add-in.

In this SharePoint site collections, I have deployed some SharePoint hosted add-ins.

If you will run the below code it will give you all the sites including the Add-in webs of the site collection from SharePoint Online.

public static void GetAllSubSites()
{
Hashtable mySites = new Hashtable();
ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana");
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
var web = context.Web;
context.Load(web, w => w.Webs);
context.Load(web, w => w.WebTemplate);
context.ExecuteQuery();
foreach (Web orWebsite in web.Webs)
{
if (orWebsite.WebTemplate != "APP")
{
context.Load(orWebsite, w => w.Title, w => w.Url);
context.ExecuteQuery();
mySites.Add(orWebsite.Url, orWebsite.Title);
}
}
}

private static SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "[email protected]<[email protected]>";
            }
            catch
            {
                throw;
            }
        }

All the sites you can see like below:

get all subsites in sharepoint online csom

But sometimes we might not need all our Add-in webs. So we can filter based on the Site template while retrieving all the subsites programmatically in SharePoint.

public static void GetAllSubSites()
{
Hashtable mySites = new Hashtable();
ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana");
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
var web = context.Web;
context.Load(web, w => w.Webs);
context.ExecuteQuery();
foreach (Web orWebsite in web.Webs)
{
context.Load(orWebsite, w => w.Title, w => w.Url);
context.ExecuteQuery();
mySites.Add(orWebsite.Url, orWebsite.Title);
}
}

private static SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "[email protected]<[email protected]>";
            }
            catch
            {
                throw;
            }
        }

Now if you will check I have only 3 sites which it is returning and is required.

Get all subsites from a site collection in SharePoint Online using CSOM

Get Subsites of a SharePoint Online Site Collection using PowerShell

Now, let us see, how to get or retrieve all the subsites from a site collection in SharePoint Online Office 365 using PowerShell.

A user wants to see the list of all the subsites in a given Site Collection in SharePoint Online. It is unfortunate that my site collection was pretty old and was filled with many subsites with multiple levels. So it is closely impossible to harvest the information manually without any slippage.

Below is the PowerShell Script to retrieve subsites from a SharePoint Online site collection.

<# This Script is to get all the subsites in a given site collection from SPO #>

function GetSubSiteDetails {
try {
#Reading artifacts/prerequisites
$strSiteCollURL = Read-Host "Enter the Site Collection URL of SPO (eg. https://onlysharepoint2013.sharepoint.com/sites/krishna)"
$strUserId = Read-Host "Enter the username of SPO (eg. [email protected])"
$strPassword = Read-Host "Please enter the password for $($strUserId)" -AsSecureString

$startedTime = Get-Date
Write-Host "Time Started = " $startedTime
Write-Host "`nAll the Sub Sites in Site Collection $($strSiteCollURL) are::"

#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.Client\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.Client.Runtime\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.Runtime.dll"

#Bind to site collection
$ObjContext = New-Object Microsoft.SharePoint.Client.ClientContext($strSiteCollURL)
$ObjCreds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($strUserId,$strPassword)
$ObjContext.Credentials = $ObjCreds
#Iterating through the Site Collections
Get-SPOWebs($strSiteCollURL)

$completedTime = Get-Date
Write-Host "`nTime Completed = " $completedTime
Write-Host "Script Excecuted Successfully !!!"
}
catch {
write-host "Error: $($_.Exception.Message)" -foregroundcolor red
}
}
function Get-SPOWebs($url) {
#Creating object to Site Collection
$objClientCntx = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$objClientCntx.Credentials = $ObjCreds
$objWeb = $objClientCntx.Web
$objClientCntx.Load($objWeb)
$objClientCntx.Load($objWeb.Webs)
try {
$objClientCntx.ExecuteQuery()
#Iterate through all the subsites in a site collection
foreach ($objWeb in $objWeb.Webs) {
write-host "Site Name::$($objWeb.Title)`t`t Site URL :: $($objWeb.url)" -foregroundcolor green
Get-SPOWebs($objWeb.url)
}
}
catch {
write-host "Could not find web" -foregroundcolor red
}
}
GetSubSiteDetails
<# To run this script you need to set the PowerShell Command-let execution policies as follows
Check the execution policies
Get-ExecutionPolicy -List
Step 2 Set the execution policy to "RemoteSigned" with the below command
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Step 3 Execute the PS1
Step 4 remove the execution policies
Set-ExecutionPolicy Undefined -Scope LocalMachine
#>

The above script has made my life simply and smooth. The output will be as follows:

Get Subsites of a SharePoint Online Site Collection using PowerShell

This PowerShell SharePoint Online tutorial explains how to retrieve all subsites under a site collection using PowerShell in SharePoint Online Office 365.

Here we checked, how to retrieve all the subsites from a site collection using .Net client object model (csom) code. It will display all the subsites other than the SharePoint hosted add-in subsites.

You may like following SharePoint site collection tutorials:

Hope this SharePoint tutorial explains, how to create a SharePoint site or subsite in SharePoint Online.

  • Create site in SharePoint Online or SharePoint 2013/2016/2019
  • Create subsite in SharePoint 2013 Online programmatically using CSOM
  • SharePoint Check if subsite exists using CSOM
  • Create subsite in SharePoint Online programmatically
  • Create subsite in SharePoint programmatically using server object model
  • Create subsite in SharePoint programmatically using csom (client side object model)
  • Delete sites and subsites programmatically using CSOM in SharePoint Online
  • Get all subsites from a site collection in SharePoint Online using CSOM
  • Get all subsites from a site collection in SharePoint using CSOM
  • Get Subsites of a SharePoint Online Site Collection using PowerShell
>