December 10, 2012

Get count of sites under a site collection uisng SharePoint Object Model

This article will describe a very simple way to calculate total no. of Sites inside a Site Collection. Below are the steps:

1. We first have to create a Uri object, which will capture the webapplication (SPwebApplication) URL. 

2. Then a Site Collection (SPSite) object can be created by selecting the appropriate site collection from the above web app.

3. Count the number of sites (SPWeb) in this site collection.

//Sample Code

Required Namespaces :


       Uri u = new Uri("MyWebAppURL");
           SPWebApplication myWebApp= SPWebApplication.Lookup(u);
           SPSite siteColName;

           siteColName = myWebApp.Sites["sites/MySiteCol"];

          Console.WriteLine("Total number of sites under this site collection : "  +     siteColName.AllWebs.Count);