Copied to clipboard

Flag this post as spam?

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

  • Sandra26 15 posts 115 karma points
    Sep 16, 2019 @ 14:01

    Getting Media file's url in C#

    Hello, I'm creating rest api using UmbracoApiController Umbraco 8 and have Umbraco 8 page. I need help finding way how to get one media file or all media files's url on Umbraco page using media file's name as an input variable. I've gone trough this thread but unfortunately it didn't work for me. I also tried with

    var media = UmbracoContext.Media.GetAtRoot().Where(m => m.Name.ToLower() == mediaName.ToLower()).FirstOrDefault();

    and with

    var media=Umbraco.MediaAtRoot().Where(m => m.Name.ToLower() == mediaName.ToLower()).FirstOrDefault();

    and they are null, even though I have saved media in the Media tab. I'll really appreciate you're helpful answers.

  • Ollie Storey 13 posts 147 karma points
    Sep 17, 2019 @ 11:09
    Ollie Storey

    When you say you are using the name. Are you referring to the name of the image that you set in the media library or the name of the property that you are selecting your image on?

  • Sandra26 15 posts 115 karma points
    Sep 17, 2019 @ 12:39

    Name of the image or name of the folder, not the media type name.

  • Ollie Storey 13 posts 147 karma points
    Sep 17, 2019 @ 13:13
    Ollie Storey

    I am guessing that you are not finding it because the image is in a folder?

    I would recommend not using the name if possible - it's much better to use the Id or guid where possible (preferably the guid)

    However, you can get all the root media items using.

    var mediaService = Current.Services.MediaService; 
    var itemsAtRoot = mediaService.GetRootMedia();

    itemsAtRoot will contain images, files and folders at the root directory of the media section. So you will then have to enumerate through the folders at that point to get the media inside each folder.

    This is going to get expensive though. Which is why getting the media by name is not preferred.

    Your logic for comparing the string names looks fine.

  • Ollie Storey 13 posts 147 karma points
    Sep 17, 2019 @ 13:15
    Ollie Storey

    Otherwise, you might be able to use a custom examine index!

    I can imagine that if you have to get the media by name, this would be the best way of doing so.

    Here is the documentation on building custom examine indexes

Please Sign in or register to post replies

Write your reply to: