Skip to content

Instantly share code, notes, and snippets.

@dampee
Created January 27, 2017 13:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save dampee/69cae264beaefc8a2fbb3f84213c34a6 to your computer and use it in GitHub Desktop.
Save dampee/69cae264beaefc8a2fbb3f84213c34a6 to your computer and use it in GitHub Desktop.
export media library (umbraco v6 + umbraco v7)
using System;
using System.IO;
using System.Web.Hosting;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Web;
using Umbraco.Web.WebApi;
/// <summary>
/// Summary description for MediaExportController
/// </summary>
public class MediaExportController : UmbracoAuthorizedApiController
{
private string targetFolder = "~/App_Data/mediaExport";
public string GetPath()
{
var fullExportPath = HostingEnvironment.MapPath(targetFolder);
if (fullExportPath == null)
{
throw new DirectoryNotFoundException(targetFolder);
}
if (Directory.Exists(fullExportPath))
{
// delete the current export
Directory.Delete(fullExportPath, true);
}
var exportDirectory = new DirectoryInfo(fullExportPath);
var rootMedias = Umbraco.TypedMediaAtRoot();
foreach (var rootMedia in rootMedias)
{
TraverseFolder(rootMedia, exportDirectory);
}
return targetFolder;
}
private void TraverseFolder(IPublishedContent rootMedia, DirectoryInfo directory)
{
// If current item is not a folder
if (rootMedia.ItemType == PublishedItemType.Media && rootMedia.DocumentTypeAlias != "Folder")
{
// store rootMedia.Path
var srcPath =
HostingEnvironment.MapPath(rootMedia.GetPropertyValue<string>(Constants.Conventions.Media.File));
var fileInfo = new FileInfo(srcPath);
try
{
System.IO.File.Copy(srcPath, directory.FullName + "\\" + fileInfo.Name);
}
catch (Exception ex)
{
//if (Debugger.IsAttached) Debugger.Break();
LogHelper.Error<MediaExportController>("could not copy", ex);
}
return;
}
// If current item is a folder,
// Create subfolder
var folderName = rootMedia.UrlName;
var newFolder = directory.CreateSubdirectory(folderName);
// and loop children
foreach (var mediaItem in rootMedia.Children)
{
TraverseFolder(mediaItem, newFolder);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment