Getting the URL of a media item from Sitecore

 If you need to get the URL of a media item from Sitecore, such as an image, it's not always as simple as just grabbing it and using a property in the item.


By default, it stores it as a string in Sitecore, so you get something like this:

<image mediaid="{C160437E-A6A9-42A6-8345-D665F9799C5B}" mediapath="/my-image" src="~/media/my-image.ashx" />



What you need is the mediaid attribute from that tag...but since it isn't an object, you can't really query it as a property.

One way to do it is to read it as XML and query it that way.  Note that you'll need to use the Sitecore.Resources.Media namespace to be able to use MediaManager:


public static string GetMediaPath(Field mediaField)
{
     string mediaPath = "";


     var file = mediaField.Value;
     if (file != null && file.Length > 0)
     {
          XmlDocument doc = new XmlDocument();
          doc.LoadXml(file);
          string mid = doc.FirstChild.Attributes["mediaid"].Value;
          Item mediaItem = Sitecore.Context.Database.GetItem(mid);
          if (mediaItem != null)
          {
               mediaPath = Sitecore.StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(mediaItem));
          }
     }


     return mediaPath;
}




That gives you the properly formatted version you want.

Popular Posts