MSJ
MSJ

Reputation: 423

Read site page contents in Sharepoint using CSOM

In my project I need to store the site pages locally. These pages may be of published or unpublished pages. I have tried with following code but unable to get contents of the page.

ClientContext clientcontext = new ClientContext(url);
   var credentials = new SharePointOnlineCredentials(userid, SecurePass);
   clientcontext.Credentials = credentials;
   Web web = clientcontext.Web;
   clientcontext.Load(web, website => website.Lists);
   clientcontext.ExecuteQuery();
   clientcontext.Load(web, website => website.Lists,
                             website => website.Lists.Where(
                             x => x.BaseTemplate == 119));

   clientcontext.ExecuteQuery();
   var _collection = web.Lists;
   foreach (var pages in _collection)
   {

       clientcontext.Load(pages);
       clientcontext.ExecuteQuery();

       CamlQuery cq = new CamlQuery();
       var pg = pages.GetItems(cq);
       clientcontext.Load(pg);
       clientcontext.ExecuteQuery();
       foreach (var item in pg)
       {
           clientcontext.Load(item);
           clientcontext.ExecuteQuery();
           var f_webPage = clientcontext.Web.GetFileByServerRelativeUrl(item.File.ServerRelativeUrl);
           clientcontext.Load(f_webPage);
           clientcontext.ExecuteQuery();

       }
  }

How can I get site pages contents? Thanks in advance.

Upvotes: 2

Views: 6125

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59378

In Site Pages library (list type of ListTemplateType.WebPageLibrary) the content for list item depending on the underling the content type could be extracted from:

  • WikiField field in case of Wiki Page
  • CanvasContent1 field in case of Site Page (aka "modern" page)

Example

var listTitle = "Site Pages";
var list = ctx.Web.Lists.GetByTitle(listTitle);
var items = list.GetItems(CamlQuery.CreateAllItemsQuery());
ctx.Load(items, icol => icol.Include( i => i["WikiField"], i => i["CanvasContent1"], i => i["FileRef"], i => i.ContentType));
ctx.ExecuteQuery();
foreach (var item in items)
{
     Console.WriteLine(">>> {0}", item["FileRef"]);
     switch (item.ContentType.Name)
     {
        case "Site Page":
          Console.WriteLine(item["CanvasContent1"]);
          break;
        case "Wiki Page":
          Console.WriteLine(item["WikiField"]);
          break;

     }    
 }

Upvotes: 4

Related Questions