Skip to content

Instantly share code, notes, and snippets.

@emmanuel-tissera-gs
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emmanuel-tissera-gs/5f1ba9318e463b520491 to your computer and use it in GitHub Desktop.
Save emmanuel-tissera-gs/5f1ba9318e463b520491 to your computer and use it in GitHub Desktop.
Insert media files into Kentico Media Library
using CMS.Base;
using CMS.IO;
using CMS.MediaLibrary;
using CMS.Membership;
using System;
namespace KenticoMediaLibraryConsole
{
internal class Program
{
// Note that this version does not push items to the Kentico Staging Queue
// See https://gist.github.com/emmanuel-tissera-gs/19ec7fe4b9135398c45f for fix
private static void Main(string[] args)
{
(new MediaFileSample()).AddMediaLibraryItem();
}
}
public class MediaFileSample
{
private UserInfo User
{
get { return CMS.Membership.UserInfoProvider.GetUserInfo("Administrator"); }
}
public void AddMediaLibraryItem()
{
CMS.Base.SystemContext.WebApplicationPhysicalPath = @"C:\inetpub\wwwroot\Site\CMS";
CMS.DataEngine.CMSApplication.Init();
var libraryName = DateTime.Now.ToString("yyyyMMdd-HHmm");
var library = CreateMediaLibrary(libraryName);
var mediaFile = GetInitializedMediaFile(library);
if (mediaFile != null)
{
MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
CMSWorkerQueue.RunCurrentQueuedWorkers();
}
}
private MediaLibraryInfo CreateMediaLibrary(string libraryName)
{
using (new CMSActionContext(User))
{
var library = new MediaLibraryInfo();
// Set the properties
library.LibraryDisplayName = libraryName + " Display";
library.LibraryName = libraryName;
library.LibraryDescription = libraryName + " Description";
library.LibraryFolder = libraryName;
library.LibrarySiteID = 1;
library.LibraryLastModified = DateTime.Now;
// Create the media library
MediaLibraryInfoProvider.SetMediaLibraryInfo(library);
return library;
}
}
private MediaFileInfo GetInitializedMediaFile(MediaLibraryInfo library)
{
MediaFileInfo mediaFile = null;
if (library != null)
{
var filePath = @"C:\Powered_by_kentico2.gif";
// Create file info
FileInfo file = FileInfo.New(filePath);
using (new CMSActionContext(User))
{
mediaFile = new MediaFileInfo(filePath, library.LibraryID)
{
FileName = file.Name,
FileTitle = "File Title",
FileDescription = "A Description for the file",
FilePath = "MyNewFile.gif",
FileExtension = file.Extension,
FileMimeType = "image/gif",
FileSiteID = 1,
FileLibraryID = library.LibraryID,
FileSize = file.Length,
FileModifiedByUserID = User.UserID
};
}
}
return mediaFile;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment