Getting Media File binary stream

Chet Tom asked on July 7, 2021 17:31

I have an imagePath coming into a GetImage() method...

        var xImage = new XImage();
        var fileName = Path.GetFileName(imagePath).Split('?')[0].Split('.')[0];

        MediaLibraryInfo imagesMediaLibrary = MediaLibraryInfoProvider.GetMediaLibraryInfo("Menu-        
            Builder_Files", SiteContext.CurrentSiteName);

        MediaFileInfo mediaLibraryImage = MediaFileInfoProvider.GetMediaFiles()
            .WhereEquals("FileLibraryID", imagesMediaLibrary.LibraryID)
            .WhereEquals("FileExtension", ".jpg")
            .WhereEquals("FileName", fileName)

I want to grab the mediaLibraryImage.FileBinaryStream, but it is null. Am I missing something here? The file is in media library. Also of note, the FileSize is not null usually around 2xxxx.

I am trying to build a menu with media library assets, but am having caching issues when I pull them in with a naked http request like this...

        using (WebClient webClient = new WebClient())
            byte[] data = webClient.DownloadData(imagePath);

            using (MemoryStream mem = new MemoryStream(data))
                mem.Write(data, 0, data.Length);

Does anybody know a native Kentico method of doing this.

Correct Answer

Dmitry Bastron answered on July 12, 2021 11:39

Hi Chet,

To your first part of the question. When you request media file via MediaFileInfoProvider it returns you only metadata stored within the database, it never returns you a file binary for performance reasons. However, if you need file binary you can request it like this:

var mediaLibrary = MediaLibraryInfoProvider.GetMediaLibraryInfo(mediaLibraryImage.FileLibraryID);
var mediaFileWithBinary = MediaFileInfoProvider.GetFile(mediaLibraryImage, mediaLibrary.LibraryFolder, SiteContext.CurrentSiteName);

As for the second part of your question, it doesn't make much sense. Could you please clarify what are you trying to achieve? Why do you need to request something through WebClient to cache?

0 votesVote for this answer Unmark Correct answer

Recent Answers

Brenden Kehren answered on July 7, 2021 20:37

By default files are only stored in the file system and not the database so you'd need to change those Site Settings to store the files in the database so that binary field is populated.

0 votesVote for this answer Mark as a Correct answer

Chet Tom answered on July 16, 2021 18:48

Thanks for responding guys!

To address the second point Dmitry, I am pulling in pdf assets that compile a pdf menu and then caching that menu so it doesn't have to be created again. But we are getting weird caching issues on Prod this route, so we want to go through the Kentico protocols.

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.