Blog

Tagged by 'library'

  • I needed to be able to pass a file that was stored in a MemoryStream into my Kentico Media Library. In my case, the file was a dynamically generated PDF.

    I couldn’t find anything on the web on how I would achieve this. So I decided to have a go creating my own method based on the Media Library API and some very basic examples, as you can see below:

    public static string AddFile(MemoryStream file, string fileName, string description, string mediaLibrayName, string folder, string fileExt)
    {
        string cleanFileName = MakeValidFileName(fileName).Replace(" ", "-");
    
        string folderDirectory = HttpContext.Current.Server.MapPath(String.Format("/MyWebsite/media/{0}/{1}/", mediaLibrayName, folder));
    
        string mediaFilePath = String.Format("{0}{1}.{2}", folderDirectory, cleanFileName, fileExt);
    
        if (!File.Exists(mediaFilePath))
        {
            #region Create File in Media Library Directory
    
            //Check if directory exists
            if (!Directory.Exists(folderDirectory))
                Directory.CreateDirectory(folderDirectory);
    
            file.Position = 0;
    
            FileStream outStream = new FileStream(mediaFilePath, FileMode.Create, FileAccess.Write);
            file.WriteTo(outStream);
            outStream.Flush();
            outStream.Close();
    
            #endregion
    
            #region Add file info to Kentico Media library
    
            //Media Library Info - takes Media Library Name and Website Name
            MediaLibraryInfo libraryInfo = MediaLibraryInfoProvider.GetMediaLibraryInfo(mediaLibrayName, CMSContext.CurrentSiteName);
    
            // Get Relative Path to File
            string path = CMS.MediaLibrary.MediaLibraryHelper.EnsurePath(mediaFilePath);
    
            //Create media file info item
            MediaFileInfo fileInfo = new MediaFileInfo(path, libraryInfo.LibraryID, folder);
    
            fileInfo.FileTitle = fileName;
            fileInfo.FileDescription = description;
    
            // Save media file info
            MediaFileInfoProvider.ImportMediaFileInfo(fileInfo);
    
            #endregion
    
            return String.Format("/MyWebsite/media/{0}/{1}/{2}.{3}?&ext=.{3}", mediaLibrayName, folder, cleanFileName, fileExt);
        }
        else
        {
            return String.Empty;
        }
    }
    

    The method I created is generic enough for you use in your own Kentico site. It provides all the necessary parameters needed  to add an image to a media library of your choice. For example:

    AddFile(fileMemStream, “Marketing Issue", “Monthly Marketing Info”, "Private", "Premium Folder", "pdf");
    

    As much as a like using the Kentico CMS platform, I find their API documentation some what lacking in examples on how to use certain methods, especially for a new Kentico developer like myself. I am hoping this is something that will change in the near future.