Imagine you are creating a page that you want in place of the default.aspx homepage that resides at the heart and soul of every Site in SharePoint.  Here’s how you do it:

//pageLayout = a page layout
//pubWeb = PublishingWeb

PublishingPage publishingPage = pubWeb.AddPublishingPage("http://sharepointtest/justanothersite/Pages/new-default.aspx", pageLayout);
publishingPage.Update();

pubWeb.DefaultPage = publishingPage.ListItem.File;
pubWeb.Update();

const string checkInComment = "Initial Check In";
publishingPage.CheckIn(checkInComment);
SPFile pageFile = publishingPage.ListItem.File;
pageFile.Publish(checkInComment);
pageFile.Approve(checkInComment);

pageFile.MoveTo(file.ListItemAllFields.ParentList.RootFolder.Url + "/default.aspx", true);
pageFile.Update();
}

The new publishing page is added to the web with the temporary url of “new-default.aspx”. Next we Update() the publishingPage to commit the add.

As we are adding a homepage, we set the DefaultPage property of the publishing web to the listitem file of the publishing page.  Remember here we have to Update() the publishing web or our change will not be reflected.

Check in and approve the file (Only appropriate if you have some kind of approval workflow set up on the site)

As the new publishing page we’re adding is the homepage, we use the MoveTo() method on the file to rename the file to default.aspx while passing the boolean parameter ‘true’ to make sure it overwrites the old ‘default.aspx’ if it is there.

© 2011 athe.la blog Suffusion theme by Sayontan Sinha