Skip to content

Instantly share code, notes, and snippets.

@jamiehowarth0
Last active August 29, 2015 14:25
Show Gist options
  • Save jamiehowarth0/1b77d0d50e43c5e248e1 to your computer and use it in GitHub Desktop.
Save jamiehowarth0/1b77d0d50e43c5e248e1 to your computer and use it in GitHub Desktop.
public static class IMediaServiceExtensions {
private const string UmbFile = "umbracoFile";
public static IMedia Copy(this IMediaService mediaService, IMedia media, IMedia newLocation, string newName = "") {
var properNewName = string.IsNullOrEmpty(newName) ? media.Name : newName;
var newMedia = (newLocation == null) ? mediaService.CreateMedia(properNewName, -1, media.ContentType.Alias)
: mediaService.CreateMedia(properNewName, newLocation, media.ContentType.Alias);
if (media.HasProperty(UmbFile)) {
// We need to call save here to get a media object ID to then put in the file path.
mediaService.Save(newMedia);
var fileSystem = FileSystemProviderManager.Current.GetUnderlyingFileSystemProvider("media");
var oldFilePath = media.GetValue<string>(UmbFile);
var newFilePath = Regex.Replace(oldFilePath, @"/\d{4,}/", string.Concat(Path.DirectorySeparatorChar, newMedia.Id.ToString(), Path.DirectorySeparatorChar));
// Next, retrieve the file if it exists, and clone it using the FSProvider
if (fileSystem.FileExists(oldFilePath)) {
using (var fs = fileSystem.OpenFile(oldFilePath)) {
fileSystem.AddFile(newFilePath, fs, false);
newMedia.Properties[UmbFile].Value = newFilePath;
}
}
}
foreach (var prop in media.Properties.Where(p => p.Alias != UmbFile)) {
newMedia.Properties[prop.Alias].Value = prop.Value;
}
mediaService.Save(newMedia);
if (media.Children().Any()) {
foreach (var child in media.Children()) {
mediaService.Copy(child, newMedia);
}
}
return newMedia;
}
public static IMedia Copy(this IMediaService mediaService, IMedia media, int newLocationId, string newName = "") {
return mediaService.Copy(media, mediaService.GetById(newLocationId), newName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment