SharePoint: Publishing Pages Programmatically

A quick snippet of code on how to publish pages (as this is something I have been asked a few times):

string pageUrl = “http://path/to/my/webpage.aspx”;

using (SPSite site = new SPSite(pageUrl))
{
    using (SPWeb web = site.OpenWeb())
    {
        // n.b Publishing web does not implement iDisposable
        PublishingWeb publishWeb = PublishingWeb.GetPublishingWeb(web);
        PublishingPageCollection webPages = publishWeb.GetPublishingPages();
        PublishingPage currentPage = webPages[pageUrl];

        SPListItem pageListItem = currentPage.ListItem;
        pageListItem.Update();

        if (pageListItem.File.CheckOutStatus != SPFile.SPCheckOutStatus.None)
        {
            pageListItem.File.CheckIn(“Message describing what was checked in”);
        }

        pageListItem.File.Publish(“Message on what was published”);
    }
}

You May Also Like

About the Author: rnowik

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.