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?
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.
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,
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):
If it's still failing after this then attach the debugger to see where it is falling over.
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:
Umbraco.Web.PublishedCache.NuCache.<>c.<.cctor>b931(IPublishedSnapshot publishedShapshot, Boolean previewing, Int32 id) +5 Umbraco.Web.PublishedCache.NuCache.19.MoveNext() +147 System.Linq.Buffer
1..ctor(IEnumerable
1 source) +217 System.Linq.I've tried refreshing the NuCache but still having no luck.
is working on a reply...