[SOLVED] MediaService: Get nested folders
j
[SOLVED: use Examine] The end goal is that if, in Media, I had a folder schema like "`~/Blog/Blog-1/`", I can find the
Id
of
/Blog-1/
so that I can then put images there through MediaService. My current approach is some sort of loop where I start at GetRootMedia, then find the "Blog" folder by name, then find the child folder by getting the ancestors of that folder, like this:
Copy code
var nameOfRootFolder = "Blog";
var nameOfChildFolder = "Blog-1";
var folder = MediaService.GetRootMedia().FirstOrDefault(x => x.Name.Equals(nameOfRootFolder));
var childrenFolder =
    MediaService.GetAncestors(folder).FirstOrDefault(x => x.Name.Equals(nameOfChildFolder));
...but that feels bad and, irrespective of any performance issues, wouldn't work past one child folder. So like, what should I do? Is this also an examine query off? And if it is an examine query, could someone give me an example of how I'd find a folder by path? Yours truly, Someone who found out that MediaService existed about 3 hours ago.
m
yep examine might be you friend.. a query on the media content for
nodeName
=
Blog-1
and
__NodeTypeAlias
of
Folder
.. will get you the id, or guid
__Key
of the media folder
j
OK. I'd like to think I'm better at using Umbraco than I was the last time Examine showed up, so I'll give it another shot. Thank you!
j
Yup, re-reading through it right now
m
you can get rid of of some magic strings..
Umbraco.Cms.Core.Constants.UmbracoIndexes.ExternalIndexName
Umbraco.Cms.Infrastructure.Examine.IndexTypes.Media
{ModelsBuilderNamespace}.Folder.ModelTypeAlias
and there is also
results.ToPublishedSearchResults(_publishedSnapshotAccessor.GetRequiredPublishedSnapshot())
rather than looping through the results with the yield return _umbracoHelper.Content(id);
though you might not need that anyways.
j
OK brilliant, that's worked magnificently (I'm now calling the query through a controller and have found that's much easier to set-up for testing, as opposed to the route hijacking approach imo). I think I might have to do a separate query to define the correct parent node, but the more I play around with Examine the more obvious that should be. Simple example following the tutorial just to test, and yes this is just getting the Ids for now.
Copy code
IEnumerable<string> ids = Array.Empty<string>();
if (_examineManager.TryGetIndex("ExternalIndex", out var index))
{
    ids = index.Searcher.CreateQuery("media")
        .NodeTypeAlias("folder")
        .And()
        .Field("nodeName", "Blog-1")
        .Execute()
        .Select(x => x.Id);
}
11 Views