How To Create Modern Site Page Using CSOM

Introduction

 
In a SharePoint modern page, we can access various SharePoint sites easily within an organization. We can also find the news from the site, frequent site which is visited and other suggested news posts as well as the events. It provides a fast and easy way to develop a modern responsive page using modern webparts.
 
For creating a modern page first, we create the list item object in the site page library and assign the correct content type with some other
additional properties to list item object.
 
Follow the code shown below,
 
Step 1
 
Set the credential for SiteUrl.
 
Step 2
 
Get the Library name.
 
Step 3
 
Add the template file in list item by giving the ServerRelativeUrl having modern page name (take modern page name as per your requirement. Here we have used "MyModernPage").
 
Step 4
 
Add the correct content type and properties for the modern page
  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         using(ClientContext ctx = new ClientContext("https://contoso.SharePoint.com/sites/NewSite")) {  
  4.             string passWord = "PassWord";  
  5.             SecureString securstr = new SecureString();  
  6.             foreach(char ch in passWord) {  
  7.                 securstr.AppendChar(ch);  
  8.             }  
  9.             ctx.Credentials = new SharePointOnlineCredentials("[email protected]", securstr);  
  10.             List Library = ctx.Web.Lists.GetByTitle("site pages");  
  11.             ctx.Load(Library);  
  12.             ctx.ExecuteQuery();  
  13.             // pagesLibrary is List object for the "site pages" library of the site  
  14.             ListItem oItem = Library.RootFolder.Files.AddTemplateFile("/sites/NewSite/SitePages/MyModernPage.aspx", TemplateFileType.ClientSidePage).ListItemAllFields;  
  15.             // Make this page a "modern" page  
  16.             oItem["ContentTypeId"] = "0x0101009D1CB255DA76424F860D91F20E6C4118";  
  17.             oItem["Title"] = System.IO.Path.GetFileNameWithoutExtension("MyModernpage.aspx");  
  18.             oItem["ClientSideApplicationId"] = "b6917cb1-93a0-4b97-a84d-7cf49975d4ec";  
  19.             oItem["PageLayoutType"] = "Article";  
  20.             oItem["PromotedState"] = "0";  
  21.             oItem["CanvasContent1"] = "<div></div>";  
  22.             oItem["BannerImageUrl"] = "/_layouts/15/images/sitepagethumbnail.png";  
  23.             oItem.Update();  
  24.             ctx.Load(oItem);  
  25.             ctx.ExecuteQuery();  
  26.             Console.WriteLine("successfully created mordern page in library");  
  27.             Console.ReadLine();  
  28.         }  
  29.     }  
  30. }  
Step 5
 
Now it's created, we can check it in the sitepage Library.