# Server Object Model to recursively loop through All Sites Collections and there sub-sites of Web-application

This is my First Post on SharePoint and I am new to SharePoint.I am listening lot of positive buzz on sharepoint.stackexchange , And i hope I too get the same support from you all folks.

My requirement for one of my Web-application(Sales Department) is to get all the Site collections and there sub-sites(including children and their children and so on) , Through Server-object Model and bind to grid.

I see lot of Power-Shell Scripts, But due to my infant stage to SharePoint I couldn't able to understand , Also my requirement is to achieve this using Server Object Model

Can any one help me how can I do this.

For iterate through All Sites Collections and their sub-sites recursively using SSOM so use this code below :

string siteurl = "Your Web Application URL";

SPSite tmpRoot = new SPSite(siteurl);
SPSiteCollection tmpRootColl = tmpRoot.WebApplication.Sites;

//Enumerate through each site collection
foreach (SPSite tmpSite in tmpRootColl)
{
//Enumerate through each sub-site
foreach (SPWeb tmpWeb in tmpSite.AllWebs)
{
//Gets a Boolean value for checking if sub-site inheriting permissions or not.
if(tmpWeb.HasUniqueRoleDefinitions)
{
//Do something
}
tmpWeb.Dispose();
}
tmpSite.Dispose();
}

• Remember to dispose the SPWeb and SPSite objects (e.g. tmpWeb.Dispose(), tmpSite.Dispose()) at the end of each loop. – user2536 Sep 25 '17 at 6:31
• Diceler | Youssef Thanks for your response , How can I loop to the sites holding unique permissions( broken Inheritance) – Ax Learner Sep 25 '17 at 7:00
• @AxLearner check the updated Answer above. – Youssef Moumen El idrissi Sep 25 '17 at 9:56