Deleting old content versions using the API

  • Updated

Sometimes the episerver configuration attribute uiMaxVersions does not work, it is instead possible to use IContentVersionRepository to delete older content versions. 

The example below is only for one content item. The code could be developed further to loop through the entire content tree - this code could be run for example in a scheduled job. Note that the user who runs the job would need to have delete permissions.
Remember to back up your database before running the code.

using System;
using EPiServer.Core;
using EPiServer.PlugIn;
using EPiServer.Scheduler;
using EPiServer.ServiceLocation;
using System.Collections.Generic;
using EPiServer.DataAbstraction;
using System.Linq;
using EPiServer;

// ...
var myContentReference = new ContentReference(166);
var versionRepository = ServiceLocator.Current.GetInstance();
IEnumerable allVersions = versionRepository.List(myContentReference);
var previouslyPublished = allVersions.OrderByDescending(c => c.Saved)
.FirstOrDefault(v => v.Status == VersionStatus.PreviouslyPublished && v.LanguageBranch == "en");

var newestPage = DataFactory.Instance.Get(allVersions.Last().ContentLink).CreateWritableClone();

int deleteCount = 0;
int count = 0;
const int VERSION_LIMIT = 2;

foreach (var content in allVersions.OrderByDescending(v => v.Status.Equals(VersionStatus.Published)).ThenByDescending(v => v.Saved))
{
	if (content.Status.Equals(VersionStatus.Published))
	{
		count++;
	}
	else
	{
		if (count > VERSION_LIMIT)
		{
			// delete
			versionRepository.Delete(content.ContentLink);
			deleteCount++;
		}
		else
		{
			count++;
		}
	}
}