I’ve often had to write code that iterates through all of the sites in a SharePoint farm. The requirement may be as simple as getting an inventory of sites, or I may need to execute code against each site such as; changing the theme, logo, or activating a feature. Whatever the case may be the logic is simple:

  1. Get all of the Web Applications
  2. For each Web Application
  3. Get all of the Site Collections
  4. For each Site Collection
  5. Get all of the Sites (webs)
  6. For each of the sites (webs) 
    • Get Site Information or Execute Code (i.e. change theme, logo, master page, activate/deactivate feature)
    • Get all of the Sub Sites (webs)
      • Repeat step 6

How its done:

Note: Before executing the code make sure that the user executing the logic has the required permissions on every site, or else it wont work. What is the required permission? It depends on what it is you are doing; chances are you’ll be executing this as an admin and should have full control. The following code will iterate through Central Administration and Shared Service Provider Sites, take caution when changing anything on those sites.

Make sure your code references the “Microsoft.SharePoint.Administration” namespace.

public void BeginProcess()
     // Get references to the farm and farm WebService objects
     // the SPWebService object contains the SPWebApplications
     SPFarm thisFarm = SPFarm.Local;
     SPWebService service = thisFarm.Services.GetValue(“”);

     foreach (SPWebApplication webApp in service.WebApplications)
        //Execute any logic you need to against the web application
        //Iterate through each site collection
        foreach (SPSite siteCollection in webApp.Sites)
            //do not let SharePoint handle the access denied 
            //exceptions. If one occurs you will be redirected
            //in the middle of the process. Handle the AccessDenied
            //exception yourself in a try-catch block

            siteCollection.CatchAccessDeniedException = false;

                 //Execute any logic you need to against the site collection
                 //Call the recursive method to get all of the sites(webs)
            catch (Exception webE)
                 //You should log the error for reference

            //reset the CatchAccessDeniedException property of the site
            //collection to true
            siteCollection.CatchAccessDeniedException = true;


public void GetWebs(SPWebCollection allWebs)
     //iterate through each site(web)
     foreach (SPWeb web in allWebs)
         if (web.Permissions.DoesUserHavePermissions(SPRights.FullMask));
             //Execute any logic you need to against the site (web) 


Updated 7/22/2008: Added code to handle access denied exceptions at the GetWebs level.
Updated 8/25/2008: Removed recursive call that was causing duplication.

Technorati Tags: ,,,

del.icio.us Tags: ,,,