Create Media Item Programmatically.
In this post we would learn how to create media item programmatically in sitecore.
In this post we would learn how to create media item programmatically in sitecore.
Many times we need to create media items programmatically like pdf,images,video,audio
from physical file ,so here I am sharing some code
through which we can create media item programmatically.
from physical file ,so here I am sharing some code
through which we can create media item programmatically.
public Item GetAndCreateFile(string sitecorePath, string sourcePath, string mediaItemName)
{
try
{
Sitecore.Data.Database master =
Sitecore.Configuration.Factory.GetDatabase(“master”);
Sitecore.Configuration.Factory.GetDatabase(“master”);
Sitecore.Data.Items.Item myItem =
master.GetItem(sitecorePath + “/” + mediaItemName);
master.GetItem(sitecorePath + “/” + mediaItemName);
if (myItem != null)
{
return myItem;
}
//
Create the options
Create the options
Sitecore.Resources.Media.MediaCreatorOptions options
= new
Sitecore.Resources.Media.MediaCreatorOptions();
= new
Sitecore.Resources.Media.MediaCreatorOptions();
//
Store the file in the database, not as a file
Store the file in the database, not as a file
options.FileBased = false;
//
Remove file extension from item name
Remove file extension from item name
options.IncludeExtensionInItemName = false;
//
Overwrite any existing file with the same name
Overwrite any existing file with the same name
options.KeepExisting = false;
//
Do not make a versioned template
Do not make a versioned template
options.Versioned = false;
//
set the path
set the path
options.Destination =
sitecorePath;
sitecorePath;
options.Destination =
options.Destination + “/” + mediaItemName;
options.Destination + “/” + mediaItemName;
//
Set the database
Set the database
options.Database =
Sitecore.Configuration.Factory.GetDatabase(“master”);
Sitecore.Configuration.Factory.GetDatabase(“master”);
//
Now create the file
Now create the file
Sitecore.Resources.Media.MediaCreator creator
= new
Sitecore.Resources.Media.MediaCreator();
= new
Sitecore.Resources.Media.MediaCreator();
MediaItem mediaItem = creator.CreateFromFile(sourcePath, options);
if (mediaItem != null)
{
return mediaItem; }
}
catch (Exception ex)
{
System.IO.File.AppendAllText(“log the error”’);
}
return null;
Now Its easy to create media item programmatically.
Happy Coding!!