Sitecoreaustralia's Blog

June 23, 2010

Creating Custom Media Items Programmatically

Filed under: Uncategorized — jerrong @ 7:41 am

Hi All,

I was working with a clients code today (they didn’t have an issue with me publishing it for everyone else) and they want a way to migrate content from an existing database. Included in this data was importing Media items into Sitecore. We have a handy helper class for this already in the shape of the MediaManager.Creator.CreateFromFile(a, b). They way it works is that Sitecore looks at the file type and uses this to determine the data template. When we create items programmatically we have the power to choose the template we base the item off, this is not the case with Media items. There is however a little trick that you can use to get around this which is highlighted in the code below.

MediaCreatorOptions md = new MediaCreatorOptions();

md.Destination = @”/sitecore/media library/images/” + <Insert File Name Here>;    // Set options

md.Database = Sitecore.Configuration.Factory.GetDatabase(“master”);   // Set options

Item mediaItem  = null;

using (new SecurityDisabler())   // Use the SecurityDisabler object to override the security settings

{

// Create Media in database from file

mediaItem = MediaManager.Creator.CreateFromFile(Path.Combine(ConfigurationManager.AppSettings["migrator_targetFileLocation"], String.Concat(fileNamePrefix, “.pdf”)), md);

}

mediaItem.ChangeTemplate(newsArticleTemplate);

The important trick is after this has all been done and the MediaItem has been created, simply change the template that the MediaItem is based off to your custom template by calling ChangeTemplate(<Insert Template Object>);

Hope this helps,

- Tim

Advertisement

1 Comment »

  1. [...] post on SitecoreAustralia’s blog mentions an easy way to create a media item that is your own custom media type, and we will be [...]

    Pingback by Sitecore: Modifying the Upload Process | Sean Holmesby's Blog — July 7, 2010 @ 2:45 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.