Update SharePoint Master Page with Code (C#)

This time I brought a code which allows you to update SharePoint master page on console project (with C#.Net and not with SPD).

We look for a site that starts with "http://moss2007/Test-Base/", check that the masterpage had the old version, and we will update the new masterpage.

For this subject, we'll have to save the masterpage on a physical file (C:). In addition, we have to approve the masterpage.

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

namespace Roi.SharePoint.UpdateMasterPage
{
  class Program
  {
    private const string oldMasterPage = "workgroup.master";
    private const string newMasterPage = "NewMaster.master";
    static void Main(string[] args)
    {
      SPWebApplication wepApp = SPWebApplication.Lookup(new Uri("http://moss2007/"));
      foreach (SPSite site in wepApp.Sites)
      {
        using (SPWeb web = site.RootWeb)
        {
          // Get the current "SPWeb" object
          if (web.Url.StartsWith("http://moss2007/Test-Base/"))
          {
            try
            {
              if (web.MasterUrl.ToLower().Contains(oldMasterPage))
              {
                //read file and upload content as bytre array
                FileStream fileReader = new FileStream(@"C:\" + oldMasterPage, FileMode.Open, FileAccess.Read);
                byte[] fileContent = ReadFully(fileReader, fileReader.Length);
                SPFile file = site.GetCatalog(SPListTemplateType.MasterPageCatalog).RootFolder.Files.Add(newMasterPage, fileContent);
                file.CheckIn("File Check In", SPCheckinType.MajorCheckIn);
                file.Approve("File Approve");
                if (PublishingWeb.IsPublishingWeb(web))
                {
                  // open publish site
                  PublishingWeb pub = PublishingWeb.GetPublishingWeb(web);
                  // change the Master Page
                  pub.MasterUrl.SetValue(pub.MasterUrl.Value.ToLower().Replace(oldMasterPage, newMasterPage), true);
                  pub.CustomMasterUrl.SetValue(pub.MasterUrl.Value, true);
                  pub.MasterUrl.SetInherit(false, true);
                  pub.CustomMasterUrl.SetInherit(false, true);
                  // save changes
                  pub.Update();
                }
                else
                {
                  // change the Master Page
                  web.MasterUrl = web.MasterUrl.ToLower().Replace(oldMasterPage, newMasterPage);
                  web.CustomMasterUrl = web.MasterUrl;
                  // save changes
                  web.Update();
                }
              }
              else // if not workgroup.master
              {
              }
              web.Update();
              System.Console.WriteLine("The web was update.");
            }
            catch (Exception ex)

            {
              System.Console.WriteLine("Error:");
              System.Console.WriteLine(ex.Message);
            }
          }
        }
      }
      // Return to calling environment : Success
      Environment.Exit(0);
    }
    /// <summary>
    /// Reads data from a stream until the end is reached. The
    /// data is returned as a byte array. An IOException is
    /// thrown if any of the underlying IO calls fail.
    /// </summary>
    /// <param name="stream">The stream to read data from</param>
    /// <param name="initialLength">The initial buffer length</param>
    public static byte[] ReadFully(Stream stream, long initialLength)
    {
      try
      {
        // If we've been passed an unhelpful initial length, just
        // use 32K.
        if (initialLength < 1)
        {
          initialLength = 32768;
        }
        byte[] buffer = new byte[initialLength];
        int read = 0;
        int chunk;
        while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
        {
          read += chunk;
          // If we've reached the end of our buffer, check to see if there's
          // any more information
          if (read == buffer.Length)
          {
            int nextByte = stream.ReadByte();
            // End of stream? If so, we're done
            if (nextByte == -1)
            {
              return buffer;
            }
            // Nope. Resize the buffer, put in the byte we've just
            // read, and continue
            byte[] newBuffer = new byte[buffer.Length * 2];
            Array.Copy(buffer, newBuffer, buffer.Length);
            newBuffer[read] = (byte)nextByte;
            buffer = newBuffer;
            read++;
          }
        }
        // Buffer is now too big. Shrink it.
        byte[] ret = new byte[read];
        Array.Copy(buffer, ret, read);
        return ret;
      }
      catch (IOException ex)
      {
        System.Console.WriteLine("Error:");
        System.Console.WriteLine(ex.Message);
        return null;
      }
    }
  }
}

Cheers,
Roi Kolbinger

Comments

Popular posts from this blog

A sharepoint list view of the current month

The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters

Export SharePoint 2010 List to Excel with PowerShell