集合中的每个图像都有一个序列化的文件路径。加载集合时,我需要从文件路径加载图像。下面的代码将不起作用,因为IsolatedStorageFileStream与用于映像的IRandomAccessStream不兼容。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;
}
}
是否有其他代码可以实现这一点?
您可以简单地使用WindowsRuntimeStreamExtension.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);
}