Assigning Media Files

Assigning Media Files

Assigning Media Files

The Sitecore.Configuration.Factory class encapsulates the general information available in the web.config file and contains methods that provide access to this information and the means to override it

This snippet uses a fields collection to reference the field

  • Returns null if the field does not exist or the field value is null
  • Does not generate inline editing controls for the Page Editor
  • Useful for field types other than simple field types

  1. Create an object for the database where the item is located - replace SitecoreDB with the name of the Sitecore database where you want to perform the update, typically “master”


C# Web Control Code

Sitecore.Data.Database db = Sitecore.Configuration.Factory.GetDatabase("SitecoreDB");

Sitecore.Data.Items.Item item = db.GetItem("itempath");

Sitecore.Data.Fields.ImageField image = item.Fields["fieldname"];

image.MediaID = item.ID;

Sitecore.Resources.Media.MediaUrlOptions options = new Sitecore.Resources.Media.MediaUrlOptions();

 image.Src = Sitecore.Resources.Media.MediaManager.GetMediaUrl(item, options);

 image.MediaPath = item.Paths.MediaPath;

 image.SetAttribute("showineditor", "1");

OR

Sitecore.Data.Database db = Sitecore.Configuration.Factory.GetDatabase("SitecoreDB");

Sitecore.Data.Items.Item item = db.GetItem("itempath");

Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions(); 

options.Database = db

options.Language = Sitecore.Globalization.Language.Current; 

options.Versioned = Sitecore.Configuration.Settings.Media.UploadAsVersionableByDefault; 

 options.Destination = "mediapath"; 

Sitecore.Resources.Media.MediaCreator creator = new Sitecore.Resources.Media.MediaCreator(); 

Sitecore.Data.Items.MediaItem media = creator.CreateFromFile("physicalfilepath", options); 

System.IO.FileInfo fi = new System.IO.FileInfo("physicalfilepath "); 

char[] dotArray = new char[] { '.' }; 

string[] result = fi.Name.Split(dotArray); 

using (new Sitecore.Data.Items.EditContext(item)) 

      media.InnerItem.Name = result[0]; 

      media.Extension = fi.Extension; 

      media.Alt = "alt text goes here"; 

      Sitecore.Data.Fields.ImageField imageField = item.Fields["fieldname"]; 

      imageField.MediaID = media.ID; 

      imageField.Src = Sitecore.Resources.Media.MediaManager.GetMediaUrl(media); 

 

}