How to get the file path of a media item in umbraco

Posted written by Paul Seal on August 11, 2016 Umbraco

UPDATED 08-Jun-2017

In Umbraco v7.6 and above, there is now a new thing called UDI. Find out more about UDI here.

So instead of your media item having a numeric id, by default it will have an id like this: umb://media/39d3ac707d634953ab52642d5037855c

Here is how you get the media url when the id is one of the new type:

string imageUrl = Model.Content.GetPropertyValue<IPublishedContent>("headerImage").Url;

7.5x and below

When using the media picker in Umbraco, it stores the id of the media item.

This post shows you how to get the file path of the item so you can use it for the src of an image or as a link to a document.

Here is how to do it inside a view or partial view:

UmbracoHelper uHelper = new UmbracoHelper(UmbracoContext.Current);
string mediaUrl = "";
if (CurrentPage.HasValue(propertyName))
{
    var mediaItem = uHelper.Media(CurrentPage.propertyName.ToString());
    mediaUrl = mediaItem.umbracoFile;
}
return mediaUrl;

Here is how to do it from a method in a class somewhere:

using Umbraco.Web;

public static string GetMediaUrlFromPropertyName(dynamic contentItem, string propertyName)
{
    UmbracoHelper uHelper = new UmbracoHelper(UmbracoContext.Current);
    string mediaUrl = "";
    if (contentItem.HasValue(propertyName))
    {
        var mediaItem = uHelper.Media(contentItem.GetPropertyValue(propertyName));
        mediaUrl = mediaItem.umbracoFile;
    }
    return mediaUrl;
}

I hope you found this useful. Let me know if you need any further help with this.