Replacing mediaitems in Sitecore

This tip is from one of my colleagues Frederik Örnfelt who read my post about Adding a file to the Sitecore Media Library. But instead of adding files, he simply wanted to replace one item with another. Replacing media items is also done using the Sitecore MediaManager and a little stream magic:

Media sourceMedia = MediaManager.GetMedia(_sourceMediaItem);
Media targetMedia = MediaManager.GetMedia(mediaItem);
targetMedia.SetStream(sourceMedia.GetStream());

Thanks Frederik. And happy easter.

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

Follow

Get every new post delivered to your Inbox.

Join 92 other followers