Get Media Item file size

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("##.#");

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in Sitecore 6 and tagged , . Bookmark the permalink.

1 Response to Get Media Item file size

  1. Pingback: Which of my old Sitecore posts are still valid in Sitecore 9? | Brian Pedersen's Sitecore and .NET Blog

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.