Wednesday, March 7, 2012

Programatically applying master page of a sharepoint site MOSS2010

In this post we will see how to Programatically set the master page of a sharepoint site.
And also make sure its subsites inherits the root site master page.
Below is the code snippet::

/// <summary>
        /// method to add master page
        /// </summary>
        /// <param name="CurrentWeb"></param>
        public void AddMasterPage(SPWeb CurrentWeb,string customMasterPage)
        {
            try
            {

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

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

                CurrentWeb.Update();

//To change master page of all subsites
                foreach (SPWeb subweb in CurrentWeb.GetSubwebsForCurrentUser())
                {

                    ChangeMasterPage(subweb, CurrentWeb.MasterUrl, CurrentWeb.CustomMasterUrl);

                }

                CurrentWeb.Update();

            }
            catch (Exception ex)
            {

            }
        }


        /// <summary>
        /// method to change master page
        /// </summary>
        /// <param name="Web"></param>
        /// <param name="pstrMasterURL"></param>
        /// <param name="pstrCustomURL"></param>
        private void ChangeMasterPage(SPWeb subWeb, string pstrMasterURL, string pstrCustomURL)
        {
            try
            {
                subWeb.AllowUnsafeUpdates = true;
                subWeb.MasterUrl = pstrMasterURL;

                subWeb.CustomMasterUrl = pstrCustomURL;

                subWeb.Update();
                subWeb.AllowUnsafeUpdates = false;
                subWeb.Dispose();

            }
            catch (Exception ex)
            {

            }


        }

Call the method as below
AddMasterPage(myweb,"mymasterpage.master");


Hope this helps...
Next Post- Programatically changing pagelayout of default.aspx page in Sharepoint

No comments:

Post a Comment

Popular Posts