Thursday 11 August 2011

Apply custom mater pages to all subsites in a site collection in sharepoint 2007

Hi,

I have seen people trying to find out the ways to apply custom master pages created in all sites in a site collection.

This many ways like a feature can be defined at site collection level that will apply the pages to all subsites in the site collection when activated or a console application can be designed that will carry out the changes. Here I am sharing my code to do the same via a console application. This code can be used in feature receiver as well with some minor changes. This takes the site collection URL as input and changes the master page accordingly.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace ApplySameMasterpage
{
    class Program
    {
        static void Main(string[] args)
        {
            String siteUrl = Console.ReadLine();
            using (SPSite site = new SPSite(siteUrl))
            {

                foreach (SPWeb web in site.AllWebs)
                {
                    //The below line is to update site master page
                    web.CustomMasterUrl = "/_catalogs/masterpage/YourMasterPage.master";
                    //The below line is to update system master page
                    web.MasterUrl = "/_catalogs/masterpage/YourMasterPage.master";
                    web.Update();
                }

            }
        }
    }
}

I hope this will help you out.

Thanks,
Rahul Rashu

No comments:

Post a Comment