Copy Client-Side Page from one site to the other SharePoint site using PnP
Softree Technology > Blogs > SharePoint > Copy Client-Side Page from one site to the other SharePoint site using PnP

Copy Client-Side Page from one site to the other SharePoint site using PnP

  • Posted by: Softree Technology

In this post, I am going to show how to copy a modern page from one site to the other SharePoint site.

we can achieve this using PnPOnline and CSOM. This code will copy the modern page into another site collection (destination location) and then, it will also copy all the page contents including web parts and other properties of a modern page to the destination page.

A Code sample is provided below:

using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core;
using OfficeDevPnP.Core.Pages;

namespace CopyModernPage
{
    class Program
    {
        static string sourceSiteUrl = string.Empty;
        static string sourceUserName = string.Empty;
        static string sourcePassword = string.Empty;
        static string destSiteUrl = string.Empty;
        static string destUserName = string.Empty;
        static string destPassword = string.Empty;
        static string pageID = string.Empty;
        static string listName = string.Empty;
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter source site url:");
            sourceSiteUrl = Console.ReadLine();
            Console.WriteLine("Please enter source user name:");
            sourceUserName = Console.ReadLine();
            Console.WriteLine("Please enter source password:");
            sourcePassword = Console.ReadLine();
            Console.WriteLine("Please enter page library name(for ex: Site Pages):");
            listName = Console.ReadLine();
            Console.WriteLine("Please enter source page id:");
            pageID = Console.ReadLine();
            Console.WriteLine("Please enter destination site url:");
            destSiteUrl = Console.ReadLine();
            Console.WriteLine("Please enter destination user name:");
            destUserName = Console.ReadLine();
            Console.WriteLine("Please enter destination password:");
            destPassword = Console.ReadLine();

            AuthenticationManager authManager = new AuthenticationManager();

            try
            {
                using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(sourceSiteUrl, sourceUserName, sourcePassword))
                {
                    //listName = "Site Pages";
                    CamlQuery query = new CamlQuery();
                    query.ViewXml = "<View><Query>"
                                        + "<Where>"
                                            + "<Eq><FieldRef Name='ID' /><Value Type='Integer'>" + pageID + "</Value>" +
                                            "</Eq>" +
                                        "</Where>" +
                                "</Query></View>";

                    Web srcWeb = clientContext.Web;
                    clientContext.Load(srcWeb, l => l.Title);
                    clientContext.ExecuteQuery();
                    string srcWebTitle = srcWeb.Title;
                    List list = srcWeb.Lists.GetByTitle(listName);
                    clientContext.Load(list);
                    clientContext.ExecuteQuery();

                    if (list != null)
                    {
                        ListItemCollection items = list.GetItems(query);
                        clientContext.Load(items);
                        clientContext.ExecuteQuery();

                        if (items != null)
                        {
                            if (items.Count > 0)
                            {
                                foreach (ListItem item in items)
                                {
                                    Console.WriteLine(item["FileLeafRef"].ToString());
                                    ClientSidePage sourcePage = clientContext.Web.LoadClientSidePage(item["FileLeafRef"].ToString());
                                    
                                    CopyPageInDestination(sourcePage, item, srcWebTitle);
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("List is not present on the site");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
            
            Console.WriteLine("Done!");
            Console.ReadLine();
        }

        private static void CopyPageInDestination(ClientSidePage sourcePage, ListItem sourceItem, string srcWebTitle)
        {
            AuthenticationManager authManager = new AuthenticationManager();

            try
            {
                using (var destClientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(destSiteUrl, destUserName, destPassword))
                {
                    Web destWeb = destClientContext.Web;
                    destClientContext.Load(destWeb, l => l.Title);
                    destClientContext.ExecuteQuery();
                    string destWebTitle = destWeb.Title;
                    ClientSidePage newPage = destClientContext.Web.AddClientSidePage(sourcePage.PageTitle+".aspx", true);

                    if (sourcePage.PageHeader.ImageServerRelativeUrl != null)
                    {
                        newPage.PageHeader.ImageServerRelativeUrl = sourcePage.PageHeader.ImageServerRelativeUrl.ToLower().Replace(srcWebTitle, destWebTitle);
                    }
                    newPage.PageTitle = sourcePage.PageTitle;
                    newPage.LayoutType = sourcePage.LayoutType;
                    
                    if (!string.IsNullOrEmpty(Convert.ToString(sourceItem["PromotedState"])))
                    {
                        if (Convert.ToInt32(sourceItem["PromotedState"]) == 2)
                        {
                            newPage.PromoteAsNewsArticle();
                        }
                    }
                    newPage.Save();


                    ListItem newPageItem = newPage.PageListItem;
                    newPageItem["CanvasContent1"] = Convert.ToString(sourceItem["CanvasContent1"]).Replace(srcWebTitle, destWebTitle).Replace(srcWebTitle, destWebTitle);
                    if (sourcePage.LayoutType != ClientSidePageLayoutType.Home)
                    {
                        newPageItem["PromotedState"] = sourceItem["PromotedState"];
                    }
                    newPageItem["PageLayoutType"] = sourceItem["PageLayoutType"];
                    newPageItem["ClientSideApplicationId"] = sourceItem["ClientSideApplicationId"];
                    newPageItem["LayoutWebpartsContent"] = sourceItem["LayoutWebpartsContent"];
                    newPageItem.Update();
                    destClientContext.ExecuteQuery();

                    newPage.Publish();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
    }
}

OutPut:

Destination Page Library Before Copy

Destination Page Library After Copy

This solution is brought to you by our SharePoint professionals.

Softree Technology employs SharePoint consultants; we are a technology services provider with the aim to help companies achieve exceptional performance through SharePoint. Our dedicated team of SharePoint consultants has the right bent of mind to understand and execute customer requirements.

Be it SPFx or SharePoint add-in developments, SharePoint 2019 developments, web part developments, migrating from SharePoint 2010/2013 to SharePoint 2013/2016/Office 365, Office 365, SharePoint hosted apps development or something else in SharePoint, we strive to deliver the best

Author: Softree Technology

Leave a Reply