sitecore create media item programmatically

Create Media Item Programmatically.

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.

public Item GetAndCreateFile(string sitecorePath, string sourcePath, string mediaItemName)

                Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
                Sitecore.Data.Items.Item myItem = master.GetItem(sitecorePath + "/" + mediaItemName);

                if (myItem != null)
                    return myItem;

                // Create the options
                Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
                // Store the file in the database, not as a file
                options.FileBased = false;
                // Remove file extension from item name
                options.IncludeExtensionInItemName = false;
                // Overwrite any existing file with the same name
                options.KeepExisting = false;
                // Do not make a versioned template
                options.Versioned = false;
                // set the path
                options.Destination = sitecorePath;
                options.Destination = options.Destination + "/" + mediaItemName;
                // Set the database
                options.Database = Sitecore.Configuration.Factory.GetDatabase("master");

                // Now create the file
                Sitecore.Resources.Media.MediaCreator creator = 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!!



Popular Posts