Copied to clipboard

Flag this post as spam?

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


  • Andrew 25 posts 148 karma points
    Jun 04, 2019 @ 14:30
    Andrew
    0

    Get all Media files in a folder

    Hi,

    I'm trying to get a media item by its name. From what I've seen I'm not able to do this, so I'm trying to get all media items in a specific folder and then check them against the name.

    However, using the code below I'm getting a NullReference error when using the code below.

    int id = 1357;
    IPublishedContent folder = Umbraco.Media(id);
    foreach(var img in folder.Children)
    {
        if(img.Name == filename)
        {
            return img;
        }
    }
    

    Where filename is a string I'm passing in. It's finding the folder and from previous tests knows it has children.

    Does anyone know what might be causing this? Or if there is a better way I could achieve what I'm trying to do?

    Thanks,

  • andy 25 posts 94 karma points c-trib
    Jun 04, 2019 @ 15:10
    andy
    0

    Hey Andrew,

    Without knowing what you are trying to achieve, it's hard to say what your best option is. However, most of your options for querying media (without going down the mediaservice route) are covered here: https://our.umbraco.com/documentation/Reference/Querying/UmbracoHelper/#working-with-media

    Regarding the NullRefs, I'd null check everything you can as follows (or similar):

       int id = 1357;
       IPublishedContent folder = Umbraco.Media(id);
        if (folder != null)
         {
            foreach (var img in folder.Children)
            {
              if (!string.IsNullOrWhiteSpace(img?.Name))
              {
                 if (img.Name.Equals(filename))
                  {
                    return img;
                   }                       
               }
             }
           }
    

    If it's still failing after this then attach the debugger to see where it is falling over.

  • Andrew 25 posts 148 karma points
    Jun 04, 2019 @ 15:45
    Andrew
    0

    Thanks Andy, really appreciate the quick response.

    I tried making your changes and its getting the error on the folder.Children.

    I've added a check to make sure that isn't null too which it passes but then still breaks.

    The stacktrace is:

    [NullReferenceException: Object reference not set to an instance of an object.]
    

    Umbraco.Web.PublishedCache.NuCache.<>c.<.cctor>b931(IPublishedSnapshot publishedShapshot, Boolean previewing, Int32 id) +5 Umbraco.Web.PublishedCache.NuCache.19.MoveNext() +147 System.Linq.Buffer1..ctor(IEnumerable1 source) +217 System.Linq.

    I've tried refreshing the NuCache but still having no luck.

Please Sign in or register to post replies

Write your reply to:

Draft