While working with publishing sites, I came across the point where I wanted to change the welcome page of the site
well the first thing which comes to our mind is to use server object model and make use of Publishing APIs and yes that’s correct , now second thought we generally plan like to get Publishing Web object and set Default Page url .. But note that Default Page property of Publishing Web is read only
So I tried some googling and came across some results and tried one and modified some code
I took help from buddy reflector to see how Microsoft has done this in some cases
Here is the sample code which I made and 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
}
}
}
}
Thank Bhushan! Good idea! Its brilliant way of changing welcome page of SharePoint. I will certainly go for it and hope that it will work great for me.
ReplyDelete