views:

250

answers:

1

Hi,

How can I delete pages from a publishing web using the SharePoint API?

Thanks, MagicAndi.

+1  A: 

The code below works for me. It was taken from this forum post. Note, it is not possible to delete a publishing page if it is set as the default landing (welcome) page.

try
{
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        using (SPSite site = new SPSite(p_sSitePath))
        {
            using (SPWeb web = site.OpenWeb())
            {
                PublishingWeb pubWeb = null;
                if (PublishingWeb.IsPublishingWeb(web))
                {
                    pubWeb = PublishingWeb.GetPublishingWeb(web);

                    foreach (SPListItem currentItem in pubWeb.PagesList.Items)
                    {
                        if(PublishingPage.IsPublishingPage(currentItem))
                        {
                            PublishingPage page = PublishingPage.GetPublishingPage(currentItem);

                            if (page.Name != pubWeb.DefaultPage.Name)
                            {
                                currentItem.File.Delete();
                            }
                        }
                    }             
                }
            }
        }
    });
}
catch (Exception ex)
{
}
MagicAndi