Add Images for my Sitecore Items through program

时间:2016-10-20 13:00:32

标签: sitecore sitecore8

I am creating Sitecore item programtically and want to add some images for my item while creating programatically.It should get that image from Sitecore media, How to do that, need help.I Know how to do that using content item

1 个答案:

答案 0 :(得分:5)

如果您只想将图像分配给字段,则必须添加以下代码:

item.Editing.BeginEdit();
ImageField imageField = item.Fields["Your Image Field"];
imageField.MediaID = new ID("IMAGE ID");
item.Editing.EndEdit();

如果要从URL动态创建图像,然后将其指定给项目,可以使用以下代码:

var destinationPath = StringUtil.EnsurePostfix('/', imagesFolder.Paths.Path);
string imageName = ItemUtil.ProposeValidItemName(model.Title);
var options = new MediaCreatorOptions
{
    Database = ItemHelpers.GetMasterDatabase(),
    Versioned = false,
    Destination = destinationPath + imageName,
    FileBased = false,
    IncludeExtensionInItemName = false,
    KeepExisting = true,
    AlternateText = imageName
};
try 
{
    WebClient cli = new WebClient();
    byte[] imgBytes = cli.DownloadData(imageUrl);
    using (var memStream = new MemoryStream(imageBytes))
    {
        Item scImage = MediaManager.Creator.CreateFromStream(memStream, imageUrl, options);
        //Publish your Item
        //scImage.ID is the one you need to assign to you image field        
    }
}
catch (Exception)
{
    //Your code
}