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
[...] 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