Delete SharePoint Page Programmatically

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 == "YOURPAGE");
            if (page != null)
            {
                //Allow modifications
                bool webAllow = web.AllowUnsafeUpdates;
                web.AllowUnsafeUpdates = true;
                SPFile file = page.ListItem.File;
                //Delete
                file.Delete();
                //Restablish default 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.