DaveGoosem
8/21/2013 - 12:21 AM

Export Sitecore Media Library Images to file system

Export Sitecore Media Library Images to file system

using System;
using System.IO;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Resources.Media;

namespace YourNamespace
{
    public partial class MediaLibraryExporter : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        public void ExportMedia(object sender, EventArgs e)
        {
            var database = Database.GetDatabase("master");
            var images = database.SelectItems("/sitecore/media library/Images/Branches/descendant::*[@@templatekey='jpeg']");

            foreach (var image in images)
            {
                var mediaItem = (MediaItem)image;
                var media = MediaManager.GetMedia(mediaItem);
                var stream = media.GetStream();

                using (var targetStream = File.OpenWrite(Path.Combine("Your output folder location", image.Name + ".jpeg" )))
                {
                    stream.CopyTo(targetStream);
                    targetStream.Flush();
                }
            }
        }

    }
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MediaLibraryExporter.aspx.cs" Inherits="RBSM.MediaLibraryExporter" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="myButton" Text="Export Images" OnClick="ExportMedia" runat="server" />
    </div>
    </form>
</body>
</html>