I recently worked at a project where I need to return the file size of the selected media item. It is actually very simple, as Sitecore has encapsulated the media item in a Sitecore.Data.Items.MediaItem class. This class contains the default fields for a media item, hence also the file size in bytes as an integer.
This small function takes a media item id (I am calling the function from an XSL, where I have the media item id in hand) and returns the size of the item in megabytes.
using Sitecore; using Sitecore.Data.Items; public string GetMediaItemSizeMB(string mediaItemID) { Item item = Context.Database.GetItem(mediaItemID); Diagnostics.Assert.IsNotNull(item, "Could not find item with id '" + mediaItemID + "'"); MediaItem mediaItem = new MediaItem(item); // You can always make another conversion double mb = (double)mediaItem.Size/1024/1024; // This format returns the mb with one digit. return mb.ToString("##.#"); }
Pingback: Which of my old Sitecore posts are still valid in Sitecore 9? | Brian Pedersen's Sitecore and .NET Blog