通过程序为我的Sitecore项目添加图像

Ran*_*ary -5 sitecore sitecore8

我正在编程方式创建Sitecore项,并希望以编程方式为我的项添加一些图像,它应该从Sitecore媒体中获取该图像,该如何做需要帮助,我知道如何使用内容项来做到这一点

小智 5

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

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

如果要从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
}
Run Code Online (Sandbox Code Playgroud)