Iterating through all Web Applications in a SharePoint farm

Iterating through SPSiteCollection and SPWebCollection is a pretty simple, because getting these collections is a simple.

SharePoint API doesn’t provide any method to get collection of all Web Applications in a farm. Here we need to write more code, than we are getting collections of SPSite or SPWeb.

  • SPWebService provides collection of SPWebApplication, but it is only a part of all Web Applications, because SPFarm have many SP Web Services.
  • Getting all services in a SP Farm:
    • SPServiceCollection services = SPFarm.Local.Services;
  • Here we should choose only Services which is of type SPWebService
    • iterating through all services in a SPServiceCollection and check which is of type SPWebService
    • if (curService is SPWebService) …
  • Now we can iterate through all services and all web applications inside them

The final code can be something like this:

 

SPServiceCollection services = SPFarm.Local.Services;

 

foreach (SPService curService in services)

{

  if (curService is SPWebService)

  {

    SPWebService webService = (SPWebService)curService;

 

    foreach (SPWebApplication webApp in webService.WebApplications)

    {

      // here you can do something with webApp

    }

  }

}

3 Comments

  • More simple implementation without a iteration through all SPService's and a checking for a SPWebService

    SPFarm farm=SPWebService.ContentService.Farm;

    SPWebApplicationCollection webAppColl = SPWebService.ContentService.WebApplications;

    if (webAppColl != null)

               {

                   foreach (SPWebApplication spWebApp in webAppColl)

                   {

    // do your stuff here

    }

    }

  • The original blog post is correct.

    The previous comment references 'SPWebService.ContentService' which only returns the current SPWebService.

    To iterate all web applications you need all SPWebService object belonging to a farm as returned by 'SPFarm.Local.Services' or 'New SPWebServiceCollection(SPFarm.Local)'.

  • Nice post. I understand some thing additional challenging on
    different sites everyday. It is going to generally be stimulating to read content from other writers
    and practice somewhat something from their store.
    I’d prefer to utilize some with that the content on my blog whether you do not
    mind. Natually I’ll offer you with a link on your internet weblog.

    Thanks for sharing.

Comments have been disabled for this content.