get - UWP:从 'get; & set;' 中的 FilePath 设置 image.source

标签 get filepath uwp bitmapimage isolatedstoragefile

集合中的每个图像都有一个序列化的文件路径。加载集合时,我需要从文件路径加载图像。下面的代码将不起作用,因为 IsolatedStorageFileStream 与用于 image.SetSource() 的 IRandomAccessStream 不兼容。

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;
        }
    }

是否有替代代码来完成此操作?

最佳答案

您可以简单地使用 WindowsRuntimeStreamExtensions.AsRandomAccessStream扩展方法:

using System.IO;
...

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

当我测试此 SetSource 时阻止了应用程序,因此我使用了 SetSourceAsync


您也许还可以像这样直接访问独立存储文件夹:

var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
    FilePath, CreationCollisionOption.OpenIfExists);

using (var stream = await file.OpenReadAsync())
{
    await image.SetSourceAsync(stream);
}

关于get - UWP:从 'get; & set;' 中的 FilePath 设置 image.source,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34499548/

相关文章:

Python 在 Windows 上的 os.listdir 行为

c# - 当集合为空时,UWP XAML 抛出未处理的异常

javascript - 使用 WinJS 实现 UWP 透明模糊效果

c# - UWP 中的 itemscontrol 不绑定(bind)到 observablecollection 项目的坐标

Android:获取所有已发送的短信? (发件箱)

PHP函数检查2个变量是否为空

php - 替换 $_GET 以使其从命令行工作

haskell - 如何在 Haskell 中创建文件及其父目录?

unix - OCaml:如何获取*当前模块*/我的项目目录的路径?

php - GET 和 PHP 中的符号