Programmatically copying pages in Episerver

Something of a brain dump here, hopefully someone else will find this useful as well:

The client requirement:

Given an existing “template” page, copy a bunch of pages but wanted the ability to decide whether to copy children pages or not. In general, you want to copy pages using this:

var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
var toCopy = new ContentReference(pageIdToCopy); // "Root" page to copy
var destination = new ContentReference(destinationPageId); // The copied pages will be created as children of this page.
contentRepository.Copy(toCopy, destination);

Now this copies the whole page subtree and it’s great, but this wasn’t what I wanted all the time. As mentioned, I wanted the ability to copy just one page and not its children.

I saw that the Copy method didn’t have an overload with a bool copyChildren parameter, so I had to find another way. With much help from my colleague Ton Nguyen (thanks Ton!), this is the final code snippet I have ended up with to achieve my goal:

var copyRoot = new ContentReference(copyRootId);
var copyTargetRoot = new ContentReference(copyTargetRootId);

var originalPage = contentRepo.Get<PageData>(copyRoot);
var clone = originalPage.CreateWritableClone();

// Set the parent to your target.
clone.ParentLink = copyTargetRoot.ToPageReference();

// This makes the content repository treat the clone as new content. 
//  Otherwise, you would be MOVING the content.
clone.ContentLink = null;
clone.ContentGuid = Guid.Empty;

// Without this, you will get a new page with no property data.
foreach (var property in clone.Property)
{
	property.IsModified = true;
}

var copied = contentRepo.Save(clone, EPiServer.DataAccess.SaveAction.Publish);

So there it is, a way to make a copy of a content instance. I like learning things like this 🙂

Leave a Comment

Your email address will not be published. Required fields are marked *