Changing MasterPage programmatically for site collection and sub-sites



using System;


using System.Collections.Generic;


using System.Text;


using Microsoft.SharePoint;


namespace CustomMaster


{


public class ChangeMaster : Microsoft.SharePoint.SPFeatureReceiver


{


 


public override void FeatureActivated(SPFeatureReceiverProperties properties)


{


SPWeb CurrentWeb = properties.Feature.Parent as SPWeb;


CurrentWeb.MasterUrl = CurrentWeb.Site.RootWeb.ServerRelativeUrl + "/_catalogs/masterpage/MyDefault.master";


CurrentWeb.CustomMasterUrl = CurrentWeb.Site.RootWeb.ServerRelativeUrl + "/_catalogs/masterpage/custom.master";


CurrentWeb.Update();


foreach (SPWeb subweb in Web.GetSubwebsForCurrentUser())


{


ChangeMasterPage(subweb, pstrMasterURL, pstrCustomURL);


}


CurrentWeb.Dispose();


}


void ChangeMasterPage(SPWeb Web, string pstrMasterURL, string pstrCustomURL)


{


Web.MasterUrl = pstrMasterURL;


Web.CustomMasterUrl = pstrCustomURL;


Web.Update();


Web.Dispose();


}


public override void FeatureDeactivating(SPFeatureReceiverProperties properties)


{


SPWeb CurrentWeb = properties.Feature.Parent as SPWeb;


CurrentWeb.MasterUrl = CurrentWeb.Site.RootWeb.ServerRelativeUrl + "/_catalogs/masterpage/default.master";


CurrentWeb.CustomMasterUrl = CurrentWeb.Site.RootWeb.ServerRelativeUrl + "/_catalogs/masterpage/default.master";


CurrentWeb.Update();


}


}


}

Skip to main content