I need to display the filename with an extension for a File type field in Sitecore SXA 10.2. The field value in content contains an Url that points to the pdf documents in Media Library.

var fileField = (FileField)item.Fields[fileFieldName];
if (fileField == null) return string.Empty;
var file = fileField.MediaItem;

Is it possible to obtain the filename with an extension using MediaItem with FileField?

2 Answers 2


Yes, it is possible. You already have MediaItem object. So I can think of 2 ways to get the filename with an extension.

1. Using MediaUrlBuilderOptions get the full URL and split it to get the filename with the extension.

You need to build the URLs by using the MediaUrlBuilderOptions classes for media items.

Sitecore.Links.UrlBuilders.MediaUrlBuilderOptions mediaUrlBuilderOptions = new MediaUrlBuilderOptions
    IncludeExtension = true,

var fileField = (FileField)item.Fields[fileFieldName];
if (fileField == null) return string.Empty;
var file = fileField.MediaItem;

string urlWithExtention = Sitecore.Resources.Media.MediaManager.GetMediaUrl(file, mediaUrlBuilderOptions);

string fileName = urlWithExtention.Split('/').Last();

2. Using string concatenation.

var fileField = (FileField)item.Fields[fileFieldName];
if (fileField == null) return string.Empty;

Sitecore.Data.Items.MediaItem file = fileField.MediaItem;

string fileName = string.Format("{0}.{1}", file.Name, file.Extension);

Hope it helps!


Try using this way.

First we need to get the instance of the XML field by its name:

Sitecore.Data.Fields.XmlField fileField = item.Fields["File"];

Now we can read the media ID using the same approach.

Sitecore.Data.ID mediaID = Sitecore.Data.ID.Parse(fileField.GetAttribute("mediaid"));

After that we can search for the media item in the context database:

Sitecore.Data.Items.MediaItem mediaItem = Sitecore.Context.Database.Items[mediaID];

If the item is found, we can read any property of the MediaItem object:

if (mediaItem != null)
    imageControl.ImageUrl = Sitecore.StringUtil.EnsurePrefix('/', mediaItem.InnerItem["Path"]);

Using the mediaItem object you can get all the properties like Extension, Name, DisplayName etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.