Access Files(images) within a media library?

James Borza asked on April 22, 2015 02:05

Within a web part/widget I have a media library selector property. That property stores the name of a media library selected. How do I get the files within that media library/folder?

I've looked in CMS.MediaLibrary.MediaLibraryHelper but I can't find anything to return a folders contents via it's code name.

Correct Answer

James Borza answered on April 22, 2015 20:40

Figured this out, here's how I did it:

using CMS.PortalControls;
using CMS.Helpers;
using CMS.MediaLibrary;

public string Images
{
    get
    {
        return ValidationHelper.GetString(GetValue("Images"), "");
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    MediaLibraryInfo folderInfo = MediaLibraryInfoProvider.GetMediaLibraryInfo(Images, CurrentSite.SiteName);
    CMS.DataEngine.InfoObjectCollection folder = folderInfo.Children.FirstOrDefault();

    foreach(var image in folder)
    {
        if (!string.IsNullOrEmpty(image.GetProperty("Guid").ToString()))
        {
            this.imagesHTML.Text += string.Format("<img src='/{0}/media/{1}/{2}' />", CurrentSite.SiteName, folderInfo.LibraryFolder.ToString(), image.GetProperty("FilePath").ToString());
        }
    }
}

Might not be the ideal way but there is nothing in the documentation so hopefully this helps someone else.

1 votesVote for this answer Unmark Correct answer

   Please, sign in to be able to submit a new answer.