add new page to site c# programmatically code example

Example: add new page to site c# programmatically

private void CreatePage(SPSite site1, string cWebUrl, string cPageLayout, string cPageName, string cPageTitle)
        {
        try
        {
            using (SPWeb spoWeb = site1.OpenWeb(cWebUrl))
            {
                PublishingWeb pWebRoot = PublishingWeb.GetPublishingWeb(site1.RootWeb);
                PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(spoWeb);
                PageLayout[] layouts = pWebRoot.GetAvailablePageLayouts();
                PageLayout pl = GetPageLayout(layouts, cPageLayout);
                if (pl != null)
                {
                    //Create My Pages
                    PublishingPage newPage = pWeb.GetPublishingPages().Add(cPageName, pl);
                    newPage.Layout = pl;
                    newPage.Title = cPageTitle;
                    newPage.Update();
                    newPage.CheckIn("");
                    pWeb.Update();
                }
            }
        }
        catch (Exception ex)
        {
            //Error Handling code
        }
    }