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
}
}
}