Update Theme for All Site collections, Sub-Sites in SharePoint

Requirement: Update new theme in for All Site collections, Sub-Sites in SharePoint

C# code to apply theme for all sites in SharePoint:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;

namespace Theme_Update
{
    class Theme_Update
    {
        static void Main(string[] args)
        {
            string site;
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Enter the Web Application URL:");
                    site = Console.ReadLine();
                }
                else
                {
                    site = args[0];
                }

                SPSite tmpRoot = new SPSite(site);
                SPSiteCollection tmpRootColl = tmpRoot.WebApplication.Sites;

                //Enumerate through each site
                foreach (SPSite tmpSite in tmpRootColl)
                {
                    //Enumerate through each web for the site

                    foreach (SPWeb tmpWeb in tmpSite.AllWebs)
                    {
                            //Apply the default theme for the current Web
                            tmpWeb.AllowUnsafeUpdates = true;
                            tmpWeb.ApplyTheme("none");
                            tmpWeb.Update();
                            tmpWeb.ApplyTheme("Custom-Theme");
                            tmpWeb.Update();
                            tmpWeb.AllowUnsafeUpdates = false;

                        //Log to a file, where the theme is applied!
                            StreamWriter SW;
                            SW = File.AppendText("E:\ThemeLog.txt");
                            SW.WriteLine(tmpWeb.Url);
                            SW.Close();

                            //Dispose of the Web Object
                            tmpWeb.Dispose();
                        }
                    //Dispose of the Site Object
                    tmpSite.Dispose();
                }
                //Dispose of the Root Site Object
                tmpRoot.Dispose();
            }

            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Theme Updater", ex.Message);
            }
        }
    }
}

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. Passionate about sharing the deep technical knowledge and experience to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *