Access the friendly URL of a media item
You can use the Sitecore.Resources.Media.MediaManager.GetMediaUrl()
method to access the friendly URL of a media item. For example, to access the friendly URL of the media item /Sitecore/Media Library/Images/Sample in the Master database:
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item sampleItem = master.GetItem("/sitecore/media library/images/sample");
Sitecore.Data.Items.Item sampleMedia = new Sitecore.Data.Items.MediaItem(sampleItem);
string url = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(sampleMedia));
Sitecore does not automatically include the leading slash character (“/”) in media URLs. This results in relative URLs for media items, which IIS resolves to the document root due to the tilde character (“~”). In solutions with very deep information architectures, relative media URLs can exceed limits imposed by the Web client or the Web server. Use the Sitecore.StringUtil.EnsurePrefix()
method as shown in the previous example to ensure media URLs include the leading slash character.
You can use the Sitecore.Resources.Media.MediaUrlOptions
class to specify media options. For example, to retrieve the URL of the thumbnail of the /Sitecore/Media Library/Images/Sample media item in the Master database:
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item sampleItem = master.GetItem("/sitecore/media library/images/sample");
Sitecore.Data.Items.MediaItem sampleMedia = new Sitecore.Data.Items.MediaItem(sampleItem);
Sitecore.Resources.Media.MediaUrlOptions mediaOptions = new Sitecore.Resources.Media.MediaUrlOptions();
mediaOptions.Thumbnail = true;
string url = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(sampleMedia, mediaOptions));