Database master = Sitecore.Configuration.Factory.GetDatabase("master");
var item = master.GetItem(new ID("{493E6479-D647-4120-A543-B20924F24978}"));
item.Editing.BeginEdit();
//I want to replace sitecore existing image from another source
item.Editing.EndEdit();
-
Clarify your exact requirement please– Gaurav AgarwalCommented Dec 28, 2022 at 5:26
Add a comment
|
1 Answer
You can use Sitecore.Data.Fields.ImageField
class to update an Image field. For example, to update the Image field named ImageField in the /Sitecore/Content/Home item
in the Master database to the /Sitecore/Media Library/Images/Sample image
:
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");
Sitecore.Data.Items.Item sampleItem =
master.GetItem("/sitecore/media library/images/sample");
Sitecore.Data.Items.MediaItem sampleMedia =
new Sitecore.Data.Items.MediaItem(sampleItem);
Sitecore.Data.Fields.ImageField imageField = home.Fields["imagefield"];
if (imageField.MediaID != sampleMedia.ID) {
home.Editing.BeginEdit();
imageField.Clear();
imageField.MediaID = sampleMedia.ID;
if (!String.IsNullOrEmpty(sampleMedia.Alt))
{
imageField.Alt = sampleMedia.Alt;
}
else
{
imageField.Alt = sampleMedia.DisplayName;
}
home.Editing.EndEdit();
}
For more reference go to - https://doc.sitecore.com/xp/en/developers/92/sitecore-experience-manager/access-image-fields.html
-
Thanks Gaurav, But i want to replace or add new image from outside of sitecore by using Memory stream or URLs– RanjeetCommented Dec 28, 2022 at 5:41
-
Then check these - sitecore.stackexchange.com/questions/1374/… briancaos.wordpress.com/2009/07/09/… Commented Dec 28, 2022 at 5:53
-
If i'm adding any image into same path getting error as "Sitecore.Exceptions.DuplicateItemNameException:". I have set existing sitecore path but not working even image name is different. Getting error for PATH only– RanjeetCommented Dec 28, 2022 at 8:13
-
The setting name “AllowDuplicateItemNamesOnSameLevel” is in Sitecore.config file under App_Config folder. Set it to false to restrict the duplication then try. Commented Dec 28, 2022 at 9:25
-
I'm using sitecore 10 headless with Docker. So not able to find above path in my project– RanjeetCommented Dec 28, 2022 at 10:42