Apply Custom Theme to SharePoint Site via CSOM

public static void ApplyTheme(ClientContext clientContext, string colorFilePath)
{
  Site site = clientContext.Site;
  Web rootWeb = site.RootWeb;
  Web currentWeb = clientContext.Web;
  clientContext.Load(site, s => s.ServerRelativeUrl);
  clientContext.Load(rootWeb, rw => rw.Language, rw => rw.Id);
  clientContext.Load(currentWeb, cw => cw.Id);
  clientContext.ExecuteQuery();

  string siteUrl = (site.ServerRelativeUrl == "/") ? String.Empty : site.ServerRelativeUrl;
  string colourFileUrl = String.Format("{0}/_catalogs/theme/15/claret.spcolor", siteUrl);

  if (rootWeb.Id.ToString() == currentWeb.Id.ToString())
  {
    List themeList = clientContext.Site.GetCatalog(Constants.ThemeCatalog);
    Folder subFolder = rootWeb.GetFolderByServerRelativeUrl(String.Format("{0}/_catalogs/theme/15", siteUrl));

    FileCreationInformation colorFile = new FileCreationInformation();
    colorFile.Content = System.IO.File.ReadAllBytes(colorFilePath);
    colorFile.Url = "claret.spcolor";
    colorFile.Overwrite = true;

    Microsoft.SharePoint.Client.File colorFileToUpload = subFolder.Files.Add(colorFile);

    clientContext.Load(colorFileToUpload);
  }

  currentWeb.ApplyTheme(colourFileUrl, null, null, true);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s