Last active
August 29, 2015 14:27
-
-
Save emmanuel-tissera-gs/5f1ba9318e463b520491 to your computer and use it in GitHub Desktop.
Insert media files into Kentico Media Library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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