Adding a file to the Sitecore Media Library programatically

I thought it was tricky to read a file from disk and add it to the Sitecore media library untill I actually look into it. Sitecore has introduced 2 classes to help with the creation: The Sitecore.Resources.Media.MediaCreator and the Sitecore.Resources.Media.MediaCreatorOptions

The Sitecore.Resources.Media.MediaCreatorOptions class is the real gem here, as it helps you pick the right database to write to, but it also creates the folders where the file must be placed. In other words; don’t worry about creating folder items yourself. Let the MediaCreatorOptions do that for you. Here is an example:


public MediaItem AddFile(string fileName, string sitecorePath, string mediaItemName)
{
  // Create the options
  Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
  // Store the file in the database, not as a file
  options.FileBased = false;
  // Remove file extension from item name
  options.IncludeExtensionInItemName = false;
  // Overwrite any existing file with the same name
  options.KeepExisting = false;
  // Do not make a versioned template
  options.Versioned = false;
  // set the path
  options.Destination = sitecorePath + "/" + mediaItemName; 
  // Set the database
  options.Database = Sitecore.Configuration.Factory.GetDatabase("master");

  // Now create the file
  Sitecore.Resources.Media.MediaCreator creator = new Sitecore.Resources.Media.MediaCreator();
  MediaItem mediaItem = creator.CreateFromFile("c:\\myfile.pdf", options);
  return mediaItem;
}

This exampel inserts the myfile.pdf into the media library and stores it as /pdffolder/uploaded/myfile:

MediaItem myFile = AddFile("c:\\myfile.pdf", "myfile", "/pdffolder/uploaded");

The MediaCreator is also available through the static implementation, Sitecore.Resources.Media.MediaManager.Creator, so if you like statics, you can use that one instead.

The MediaCreator can also create media files from a MemoryStream:


// Remember to insert the appropriate try..catch..finally blocks.
// I have refrained from using them to compress the example.
Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
// Now use the options class as I did in the previous example
// ... insert code here ...
// ...
// Read the file from stream:
FileInfo fi = new System.IO.FileInfo(fileName);
FileStream fs = fi.OpenRead();
MemoryStream ms = new MemoryStream();
ms.SetLength(fs.Length);
fs.Read(ms.GetBuffer(), 0, (int)fs.Length);
ms.Flush();
fs.Close();
// Now create the file in Sitecore. This time I'll use the static implementation of the MediaCreator
Item mediaItem = Sitecore.Resources.Media.MediaManager.Creator.CreateFromStream(ms, fileName, options);
ms.Dispose();

Leave a Reply