getfilepathuwpbitmapimageisolatedstoragefile

UWP: Setting the image.source from FilePath in the 'get; & set;'


Each image in the collection has a serialized File Path. When loading the collection I need the image to load from the File Path. The code below will not work because IsolatedStorageFileStream isn't compatible with the IRandomAccessStream used for to image.SetSource().

public BitmapImage Image
    {
        get
        {
            var image = new BitmapImage();
            if (FilePath == null) return null;

            IsolatedStorageFileStream stream = new IsolatedStorageFileStream(FilePath, FileMode.Open, FileAccess.Read, IsolatedStorageFile.GetUserStoreForApplication());

            image.SetSource(stream);

            return image;
        }
    }

Is there alternative code to accomplish this?


Solution

  • You may simply use the WindowsRuntimeStreamExtensions.AsRandomAccessStream extension method:

    using System.IO;
    ...
    
    using (var stream = new IsolatedStorageFileStream(
        FilePath, FileMode.Open, FileAccess.Read,
        IsolatedStorageFile.GetUserStoreForApplication()))
    {
        await image.SetSourceAsync(stream.AsRandomAccessStream());
    }
    

    When I tested this SetSource was blocking the application, so I used SetSourceAsync.


    You could perhaps also directly access the Isolated Storage folder like this:

    var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
        FilePath, CreationCollisionOption.OpenIfExists);
    
    using (var stream = await file.OpenReadAsync())
    {
        await image.SetSourceAsync(stream);
    }