public static string CreatePublishingPage(ClientContext context)
{
string pageLibrary = "Pages";
string pageLayout = "MyLayout";
string pageName = "Test.aspx";
string pageDisplayName = pageName.Split('.')[0];
string pageURL = string.Empty;
try
{
Web webSite = context.Web;
context.Load(webSite);
PublishingWeb web = PublishingWeb.GetPublishingWeb(context, webSite);
context.Load(web);
if (web != null)
{
// Get Pages Library
List pages = context.Site.RootWeb.Lists.GetByTitle(pageLibrary);
ListItemCollection existingPages = pages.GetItems(CamlQuery.CreateAllItemsQuery());
context.Load(existingPages, items = > items.Include(item = > item.DisplayName).Where(obj = > obj.DisplayName == pageDisplayName));
context.ExecuteQuery();
// Check if page already exists
if (existingPages != null && existingPages.Count > 0)
{
// Page already exists
Console.WriteLine("Page already exists.\n");
pageURL = context.Web.ServerRelativeUrl + "/" + pageLibrary + "/" + PageName;
}
else
{
// Get Publishing Page Layouts
Console.WriteLine("Creating Page...\n");
List publishingLayouts = context.Site.RootWeb.Lists.GetByTitle("Master Page Gallery");
ListItemCollection allItems = publishingLayouts.GetItems(CamlQuery.CreateAllItemsQuery());
context.Load(allItems, items = > items.Include(item = > item.DisplayName).Where(obj = > obj.DisplayName == pageLayout));
context.ExecuteQuery();
ListItem layout = allItems.Where(x = > x.DisplayName == PageLayout).FirstOrDefault();
context.Load(layout);
// Create a publishing page
PublishingPageInformation publishingPageInfo = new PublishingPageInformation();
publishingPageInfo.Name = pageName;
publishingPageInfo.PageLayoutListItem = layout;
PublishingPage publishingPage = web.AddPublishingPage(publishingPageInfo);
publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
publishingPage.ListItem.File.Publish(string.Empty);
publishingPage.ListItem.File.Approve(string.Empty);
context.Load(publishingPage);
context.Load(publishingPage.ListItem.File, obj = > obj.ServerRelativeUrl);
context.ExecuteQuery();
Console.WriteLine("Page Created.\n");
pageURL = context.Web.ServerRelativeUrl + "/" + pageLibrary + "/" + pageName;
}
}
}
catch (Exception e)
{
Console.WriteLine("Failed. Error: " + e);
}
return pageURL;
}This code for Create a Publishing Page using Page Layout in SharePoint.
