Create and Publish web pages in Publishing SharePoint sites programmatically


Microsoft.SharePoint.Publishing is the assembly that we need to use to get pages created and published.  A sample is provided below:

using (SPSite site = new SPSite("http://moss"))
{
using (SPWeb web = site.OpenWeb())
{
PublishingSite pSite = new PublishingSite(site);
SPContentType ctype = pSite.ContentTypes["Welcome Page"];
PageLayoutCollection pageLayouts = pSite.GetPageLayouts(ctype, true);
PageLayout pageLayout = pageLayouts["/_catalogs/masterpage/welcomesplash.aspx"];
PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web);
PublishingPageCollection pPages = pWeb.GetPublishingPages();
PublishingPage pPage = pPages.Add("Programmatic_Test.aspx", pageLayout);
SPListItem newpage = pPage.ListItem;
newpage["Title"] = "Page added programmatically";
newpage.Update();

newpage.File.CheckIn("all looks good");
newpage.File.Publish("all looks good");
}
}

This is an easy way of automating creating & publishing pages in collaboration/publishing sites, especially when the need is to create/publish them at a larger scale.  I hope this tip is helpful!

Comments (9)

  1. Ganapati says:

    Hi Sridhar,

    Can we design a web user control and add this to a web part in SharePoint?

    Please pass me some info.

  2. karthik says:

    Sridhar,

    Is there a way to add data View webparts and Custom webparts to the newly added page programmatically?

    I have a dataview webpart that consumes a webservice.

  3. Hi Karthik,

    Yes you can make use of SPWebPartManager class and add web parts to different zones at runtime.

    Sorry, I don’t have any code samples yet to show how to do it, but it’s possible.

    Cheers,

    Sridhar

  4. Priyanka says:

    Hi,

    The way you have created a new publishing page, is there a way I can add it to a document library somehow?

    or is there any other way of doing it? I want to add new .aspx page in a document library that has content type set on it.

    Any help would be great.

    Thanks,

    Priyanka

  5. Ranju singh says:

    Hi,

      i’ve a table in sql database,i want to access that data and display in a list in sharepoint.what is the code? (without using BDC)

    any help would be great

     Thanks

      Ranju

  6. Rami Salem says:

    Can we use share point to develop a social network and publish it on the internet so every one can use it with their user name and password

  7. Rami Salem says:

    Can we use share point to develop a social network and publish it on the internet so every one can use it with their user name and password

Skip to main content