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;

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

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

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>