ScheduledPlugIn - how to delete unpublished/old versions of MediaData

Vote:
 

I have some code thats gets files from a service. If a file is changed i will first update the file and after delete the old versions of this content (do this to save disk space)

When i try to delete old versions i get this error in my logs

EPiServer.Core.AccessDeniedException: Access was denied to content 13893_94956. The required access level was "Delete".

This line fails

versionRepository.Delete(epiFileVersion.ContentLink);

How to fix this?

Entire code

// Will delete previous versions of pdf file
public static void DeletePreviousGenericMediaVersion(ContentReference epiFileRef)
{
var epiFileVersions = versionRepository.List(epiFileRef);

foreach (var epiFileVersion in epiFileVersions)
{
// Delete all unpublished file versjons
if (epiFileVersion.Status != VersionStatus.Published)
{
// Before we delete the content we need to clean up blob data on disk. To do this we need BinaryData ID
var epiFileVersjonContent = Repository.Get(epiFileVersion.ContentLink);
BlobFactory.Delete(epiFileVersjonContent.BinaryData.ID);
versionRepository.Delete(epiFileVersion.ContentLink);
}
}
}
#180432
Jul 10, 2017 13:53
Vote:
 

Hey, Øyvind,

Are you doing this from a scheduled job? Can you add the following before you start deleting:

EPiServer.Security.PrincipalInfo.CurrentPrincipal = EPiServer.Security.PrincipalInfo.CreatePrincipal(some_admin_user_who_has_delete_rights); 

BR,
Marija

#180646
Jul 19, 2017 12:00
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.