Checkin/Publish and Unpublish/Checkout SharePoint Pages Programmatically

Unpublish and Checkout SharePoint Page:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite("YOURSITE"))
    {
        using (SPWeb web = site.OpenWeb())
        {
            //Obtain the Page
            PublishingPageCollection publishingPages = PublishingWeb.GetPublishingWeb(web).GetPublishingPages();
            PublishingPage page = publishingPages.FirstOrDefault(f => f.Uri.AbsoluteUri == "YOURPAGEURL");
            if (page != null)
            {
                //Allow file modifications
                bool webAllow = web.AllowUnsafeUpdates;
                web.AllowUnsafeUpdates = true;
                SPFile file = page.ListItem.File;
                //Unpublish
                file.UnPublish("Page unpublished");
                //Checkout
                file.CheckOut();
                //Restablish default modification permissions
                web.AllowUnsafeUpdates = webAllow;
            }
            else
            {
                throw new Exception("Page Not Found");
            }
        }
    }
});

CheckIn and Publish SharePoint Page:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite("YOURSITE"))
    {
        using (SPWeb web = site.OpenWeb())
        {
            //Obtain your page (I've done this way)
            PublishingPageCollection publishingPages = PublishingWeb.GetPublishingWeb(web).GetPublishingPages();
            PublishingPage page = publishingPages.FirstOrDefault(f => f.Uri.AbsoluteUri == "MYURLPAGE");
            if (page != null)
            {
                //Allow modifications
                bool webAllow = web.AllowUnsafeUpdates;
                web.AllowUnsafeUpdates = true;
                SPFile file = page.ListItem.File;
                //Checkin
                file.CheckIn("Checkin done");
                //Publish
                file.Publish("Publish done");
                //Restablish default modification permissions
                web.AllowUnsafeUpdates = webAllow;
            }
            else
            {
                throw new Exception("Page Not Found");
            }
        }
    }
});

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.