Jevgeni Borozna's blog

SharePoint, ASP .NET

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

    }

  }

}

Comments

WebDevVote.com said:

You are voted (great) - Trackback from WebDevVote.com

# December 28, 2009 5:22 AM

Catalin said:

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

}

}

# October 21, 2011 3:32 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)