Changing Welcome Page of SharePoint site Programmatically



While working with publishing sites, I came across a requirement to change the welcome page of the site.

Well the first thing which comes to mind is to use a server object model and make use of the Publishing APIs and yes that's good; now a second thought woiuld be a general plan such as getting a Publishing Web object and setting the Default Page url, but note that the Default Page property of the Publishing Web is read only.

So I tried some googling and came across some results and tried one and modified the code.

I utilized our buddy the reflector to see how Microsoft has done this in some cases.

Here is the sample code I wrote and that works fine for me.

namespace ChangeWelcomePage
{
 class Program
 {
  static void Main(string[] args)
  {
   try
   {
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
     using (SPSite site = new SPSite("http://siteName:port"))
     {
      using (SPWeb web = site.OpenWeb())
      {
       web.AllowUnsafeUpdates = true;
       if (PublishingWeb.IsPublishingWeb(web))
       {
        PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);

        if (publishingWeb != null)
        {
         SPFolder rootFolder = web.RootFolder;
         SPFolder pagesFolder = publishingWeb.PagesList.RootFolder;
         try
         {
         //Ensuring Root Folder
          if (rootFolder != null)
          {
            //Ensuring Pages Root Folder
            if (pagesFolder != null)
            {
              string newWelcomePageUrl = publishingWeb.PagesList.Title + "/" + "YourPage.aspx";
              rootFolder.WelcomePage = newWelcomePageUrl;
                                               
              if (newWelcomePageUrl.StartsWith(pagesFolder.Url, StringComparison.OrdinalIgnoreCase))
              {
                pagesFolder.WelcomePage = newWelcomePageUrl.Substring(publishingWeb.PagesList.RootFolder.Url.Length + 1);
                                                    pagesFolder.Update();
              }

                 rootFolder.Update();
                 web.Update();
                 publishingWeb.Update();
                 Console.WriteLine("done");
             }
            }
        }
     catch (Exception ex)
     {
       Console.WriteLine(ex.Message);
     }
     finally
     {
       if (publishingWeb != null)
       {
         publishingWeb.Close();
       }
     }
    }

   }
    web.AllowUnsafeUpdates = false;
   }
   }
  });
   Console.ReadLine();
 }
 catch (Exception ex)
 {
     //handle exception
 }
 }
 
}
}
 

Up Next
    Ebook Download
    View all
    Learn
    View all