Get Web Object from SharePoint Using CSOM (PnP Core Component)

PnP core component contains the extension methods which help to achieve the SharePoint task in simple lines of code. So to know more about PnP Core component, have a look at:

WebExtensions.GetWeb

(PnP Core Component) - This extension method returns the child web site based on the specified leaf url. For now, the retrieved the web site only returns the server relative url of the website.

Supports: SharePoint 2013, SharePoint 2016, SharePoint Online
Assembly: OfficeDevPnP.Core.dll
Namespace: Microsoft.SharePoint.Client

Method

Web GetWeb( string leafUrl )

Syntax

Single Line Code: Web.GetWeb(“subsiteurl”)

Code Snippet

The following example returns the child site’s server relative url.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.SharePoint.Client;  
  7. using OfficeDevPnP.Core;  
  8.   
  9. namespace PnPSitesCore.Samples  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             string siteUrl = "https://sharepointonline.sharepoint.com";  
  16.   
  17.             AuthenticationManager authManager = new AuthenticationManager();  
  18.   
  19.             //Interactive Login to SharePoint site - Opens a Online signin page to authenticate the user  
  20.             var context = authManager.GetWebLoginClientContext(siteUrl);  
  21.   
  22.             //The below GetWeb method returns the website based on the url “subsite” from the parent site  
  23.             Web oweb = context.Web.GetWeb("subsite");  
  24.             Console.WriteLine(oweb.ServerRelativeUrl);  
  25.   
  26.             Console.WriteLine("Press any key to exit.");  
  27.             Console.ReadKey();  
  28.         }          
  29.     }  
  30. }  

The above code isalso available from GitHub.

Note

The returned Web object returns only the server relative url property. If we access other properties from the object, that return a "field or property not initialized" error.