kenticomedia-library

Kentico 11 - MediaFileInfoProvider.DeleteMediaFileInfo Not Deleting


MediaFileInfo updateFile = MediaFileInfoProvider.GetMediaFileInfo(library.LibraryID, file.Name);

The above line of code is not removing the file from the media library as I expected. This is for a Scheduled Task in Kentico 11 MVC. The new file does get created and is renamed by the System to prevent conflicts. I would like to delete the existing file before importing the updated version of the file. I would even be satisfied if the new file overwrote the existing file.

public void UpdateMediaFile(MediaLibraryInfo library, string fileName, string importPath) { //LumberMarketReport.pdf and PanelMarketReport.pdf

        if (library != null)
        {
            // Prepares a path to a local file
            string filePath = fileName;

            // Prepares a CMS.IO.FileInfo object representing the local file
            CMS.IO.FileInfo file = CMS.IO.FileInfo.New(filePath);

            if (file != null)
            {
                #region "Delete Existing"
                MediaFileInfo updateFile = MediaFileInfoProvider.GetMediaFileInfo(library.LibraryID, file.Name);

                if (updateFile != null)
                {
                    MediaFileInfoProvider.DeleteMediaFileInfo(updateFile);
                }
                #endregion


                #region "Create File"
                // Creates a new media library file object
                MediaFileInfo mediaFile = new MediaFileInfo(filePath, library.LibraryID);

                // Sets the media library file properties
                mediaFile.FileName = file.Name;

                mediaFile.FileDescription = "This file was added through the API.";
                mediaFile.FilePath = "/"; // Sets the path within the media library's folder structure
                mediaFile.FileExtension = file.Extension;
                mediaFile.FileMimeType = MimeTypeHelper.GetMimetype(file.Extension);
                mediaFile.FileSiteID = SiteContext.CurrentSiteID;
                mediaFile.FileLibraryID = library.LibraryID;
                mediaFile.FileSize = file.Length;

                if (file.Name == "PanelMarketReport.pdf")
                {
                    mediaFile.FileTitle = "Panel Market Report";
                    mediaFile.SetValue("FileCategoryID", 19);
                }
                else if (file.Name == "LumberMarketReport.pdf")
                {
                    mediaFile.FileTitle = "Lumber Market Report";
                    mediaFile.SetValue("FileCategoryID", 57);
                }

                // Saves the media library file
                MediaFileInfoProvider.SetMediaFileInfo(mediaFile);


                #endregion

            }
        }
    }

Solution

  • I would add logging to make sure your code is getting hit. Make sure updatefile isn't null. I think you have to pass in the file path in the media library and not just the name.