Create Subsite Programmatically using PnP in SharePoint Online

In this SharePoint PnP tutorial, We will discuss how to create a Subsite programmatically using PnP in SharePoint Online.

The PnP SharePoint code will check if the site is already exists or not. If the site exists, then it will just display a message and if the site is not presented, then it will create the site in SharePoint Online.

SharePoint Online pnp create a subsite

Below, is the code to create a subsite using PnP CSOM SharePoint. Here I have create a asp.net web application and added the required dll to work with PnP in SharePoint Online.

If you are new to PnP SharePoint, check out an article on SharePoint Online Development using Patterns and Practices (PnP).

public void CreateSubSite(string siteName)
        {            
            try
            {
                AuthenticationManager authManager = new AuthenticationManager();
                var context = authManager.GetWebLoginClientContext(txtSiteUrl.Text);
                Web subSiteWeb = context.Site.RootWeb;
                if (subSiteWeb.WebExists(siteName))
                {
                    lblMessage.Text = "Subsite Already Exists";
                }
                else
                {
                    Web web = context.Site.RootWeb.CreateWeb(new OfficeDevPnP.Core.Entities.SiteEntity()
                    {
                        Title = siteName,
                        Url = siteName.Replace(" ", string.Empty),
                        Description = "Site creating for testing purpose",
                        Template = "STS#0",
                        Lcid = 1033
                    },
                true, true);
                    lblMessage.Text = "Subsite created successfully";
                }
            }                
            catch (Exception)
            {
                throw;
            }
        }
    }
}

Create subsite under SharePoint Online site collection using PnP

Now, we will see how to how to create and delete subsite in a site collection using PnP core csom Library in SharePoint Online.

The below references we have to use in the code to work with PnP libraries in SharePoint:

  • Microsoft.SharePoint.Client
  • OfficeDevPnP.Core

Following functions are used for creating web in SharePoint Online:

  • WebExistsByTitle() used to check the web exists or not in the site collection.
  • CreateWeb() used to create a new web in the site collection.

See the syntax of the CreateWeb() used in our code for creating sub site.

CreateWeb(“TSInfoNew”, “TSInfoSubsite”,”New SubSite”,”STS#0″,1033,true, true);

  • “TSInfoNew”: it is the title of the Web.
  • “TSInfoSubsite”: it is the leafUrl of the web.
  • “New SubSite”: Description of the web.
  • “STS#0 “: “Team site” template code.
  • “true”: Inheritance permissions from the parent site collection.
  • “true”: inherit navigation from the Pare site collection.

Here I have created an asp.net application and I have added a button. Just click on the button, Subsite will be created in Site Collection of SharePoint Online using the PnP core CSOM library.

<div>
<asp:Button ID="btnCreateSubSite" runat="server" Text="Create Subsite" OnClick="btnCreateSubSite_Click"/><br />
<asp:Label ID="lblCreateSubSite" runat="server" Text=""></asp:Label>
</div>

Below given snippet code is creating sub site under the parent site collection of SharePoint online using PnP.

AuthenticationManager authMgr = new AuthenticationManager();
string siteURL = "https://onlysharepoint2013.sharepoint.com/sites/TSInfoPNP";
string userName = "*******@onlysharepoint2013.onmicrosoft.com";
string password = "******";
protected void btnCreateSubSite_Click(object sender, EventArgs e)
{
	createSubSite();
}
void createSubSite()
{
string subSiteName = "TSInfoNew";			
try
{
using (var ctx=authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteURL,userName,password))
{
ctx.Load(ctx.Web);
ctx.ExecuteQueryRetry();
bool subsite = ctx.Site.RootWeb.WebExistsByTitle(subSiteName);
if (!subsite)
{
Web subweb = ctx.Site.RootWeb.CreateWeb("TSInfoNew", "TSInfoSubsite","New Subsite","STS#0",1033,true, true);
ctx.Load(subweb);
ctx.ExecuteQueryRetry();
lblCreateSubSite.Text = "Sub Site Created Successfully";	
}
else{
lblCreateSubSite.Text = "Subsite already exists";
}		
}
}
catch (Exception ex)
{
lblCreateSubSite.Text = "Problem deleting Sub Site";
}
}

Run our application and then click on button “Create Subsite”.

create sub site SharePoint online programmatically using PnP core csom
create sub site SharePoint online programmatically using PnP core csom

Now our new sub site is created under site collection of SharePoint online.

create sub site SharePoint online programmatically using PnP
create sub site SharePoint online programmatically using PnP core csom

Delete Subsite from SharePoint Online Site Collection using PnP

Following functions are used for deleting web in SharePoint Online:

DeleteWeb() function is used to delete the web from the SharePoint Online Site collection.

AuthenticationManager authMgr = new AuthenticationManager();
string siteURL = "https://onlysharepoint2013.sharepoint.com/sites/TSInfoPNP";
string userName = "*******@onlysharepoint2013.onmicrosoft.com";
string password = "****";
protected void btnDeleteSubSite_Click(object sender, EventArgs e)
{
	deleteSubSite();
}
void deleteSubSite()
{
string subSitename = "TSInfoNew";
string leafURL = "TSInfoSubsite";
try
{
using (var ctx=authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteURL,userName,password))
{
ctx.Load(ctx.Web);
ctx.ExecuteQueryRetry();
bool subsite = ctx.Site.RootWeb.WebExistsByTitle(subSitename);
if (subsite)
{
var deleteweb = ctx.Site.RootWeb.DeleteWeb(leafURL);
ctx.ExecuteQueryRetry();
lblCreateSubSite.Text = "Sub Site deleted Successfully";
}
else
{
lblCreateSubSite.Text = "Subsite not exists";
}
}
}
catch (Exception ex)
{
lblCreateSubSite.Text = "Problem in deleting Sub Site";
}
}

Run your application and click on the button”Delete SubSite”, Then we will get the message like “Page Not Found” after subsite is deleted successfully from the Site Collection.

delete subsite SharePoint programmatically using PnP Core CSOM
delete subsite SharePoint programmatically using PnP Core CSOM

Get all SharePoint subsites programmatically using PnP CSOM

Below is the full PnP SharePoint Online csom code to retrieve all subsites in a site collection programmatically using PnP CSOM in SharePoint Online. The same code you can use in SharePoint 2016/2013 also, but you need to refer the dll required for SharePoint 2016/2013 from NuGet packages.

The below references we have to use in the code to work with PnP libraries:

  • Microsoft.SharePoint.Client
  • OfficeDevPnP.Core

Following functions are used for Getting all web URLs in SharePoint Online:

  • GetAllWebUrls() functions is used to get all web URLs from Site collection.

Here I have created an asp.net application and I have added a button. Just click on the button, Get all webs from the Site Collection of SharePoint Online using the PnP core CSOM library.

<div>
<asp:Button ID="btnRetrieveSiteUrls" runat="server" Text="Retrieve Site URLs" OnClick="btnRetrieveSiteUrls_Click"/><br />
<asp:Label ID="lblRetrieveSiteUrls" runat="server" Text=""></asp:Label>
</div>

Below given snippet code get all subsites from site collection of SharePoint online using PnP.


protected void btnRetrieveSiteUrls_Click(object sender, EventArgs e)
{
	retrieveSiteUrls();
}

void retrieveSiteUrls()
{
try
{
using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteURL, userName, password))
{
ctx.Load(ctx.Web);
ctx.ExecuteQueryRetry();
var siteURLCollection = ctx.Site.GetAllWebUrls();
foreach (var siteUrls in siteURLCollection)
{
lblRetrieveSiteUrls.Text += siteUrls +"<br/>";
}
ctx.ExecuteQueryRetry();
}
}
catch (Exception ex)
{
//lblRetrieveSiteUrls.Text = ex.StackTrace;
lblRetrieveSiteUrls.Text = "Problem in retriving Site Urls";
}
}

Run your application and click on Button “Retriev Site URLs” on the page. Now you will get all Susbsites from the site collection of SharePoint online.

SharePoint-get-all-subsites-programmatically using PnP core csom Library
SharePoint-get-all-subsites-programmatically using PnP core csom Library

I hope, this SharePoint PnP tutorial explains, how to create a subsite programmatically using PnP in SharePoint Online.

You may like the following SharePoint tutorials:

Also, we discussed how to delete a subsite programmatically using pnp csom in SharePoint Online. Also, we checked how to get all SharePoint subsites programmatically using PnP CSOM.

>