Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at

  • Koen van Ras 56 posts 361 karma points c-trib
    Apr 22, 2020 @ 15:34
    Koen van Ras

    Get IMedia children in Umbraco 8


    I'm trying to get all the child folders of a media folder in Umbraco 8. I'm using the MediaService to get a root media item (folder) like this:

    var challengesRootFolder = ms.GetRootMedia().FirstOrDefault(x => x.Name.InvariantEquals("Challenges"));

    Now I can use the MediaService to check if the IMedia item has children using the .HasChildren() method.

    Is there any way to get all the child folders as IEnumerable<IMedia> from the challengesRootFolder in the code snippet?

  • Kevin Jump 1996 posts 12598 karma points MVP 5x c-trib
    Apr 22, 2020 @ 15:51
    Kevin Jump


    you can get the child items through

            ms.GetPagedChildren(item.Id, 0, 100, out long total);

    this would get the first 100 items (nothing but performance stopping you upping the pageSize variable)

    a more comprehensive way to get everything

    const int pageSize = 500;
    var page = 0;
    var total = long.MaxValue;
    while(page * pageSize < total)
      var children = ms.GetPagedChildren(item.Id, page++, pageSize, out total);
      // do stuff wit the child items

    Also GetPagedDescendants will get all items down the tree.

    Update: Just getting folders is a little more complex, but you can see how Umbraco does it in the source for the media controller

  • Koen van Ras 56 posts 361 karma points c-trib
    Apr 22, 2020 @ 16:20
    Koen van Ras

    Thanks this worked! I managed to get only folders by simply adding a Where to check the ContentType.Alias in the while loop. Like this:

    children.AddRange(ms.GetPagedChildren(challengesRootFolder.Id, page++, pageSize, out total)
                        .Where(x => x.ContentType.Alias == Constants.Conventions.MediaTypes.Folder));
  • Wojciech Tengler 88 posts 161 karma points
    Oct 25, 2021 @ 15:19
    Wojciech Tengler

    Thread is quite old but I think that anyone should know that your last answer contains common pitfall which can be replicated.

    GetPagedDescendanst returns IEnumerable not IQuerable so it is huge difference in performance.

    You should use proper IQuery filter as parameter to this method instead.

Please Sign in or register to post replies

Write your reply to: