开发者社区 问答 正文

wp7 从独立存储空间里读取图片:报错

我从独立存储空间里读取图片的方法

using (IsolatedStorageFileStream Stream = isf.OpenFile("_Course/Image/" + Img_str + ".jpg", FileMode.Open, FileAccess.Read))
                        {
                            if (Stream.Length==0)
                            { bi.SetSource(null); }
                            else
                                bi.SetSource(Stream);
                        }

但是,如果该图片文件不存在, bi.SetSource(null)这里实现不了。

我想求教,当独立存储空间里的图片不存在时, bi.SetSource()里的该怎么写。

谢谢

 

展开
收起
kun坤 2020-06-07 16:06:40 404 分享 版权
阿里云 AI 助理回答

在您的代码段中,当尝试读取不存在的图片文件时,直接将null赋值给bi.SetSource()似乎不被允许。您需要确保传递给SetSource方法的是一个有效的数据流。如果文件不存在,您可以考虑创建一个空的内存流(MemoryStream)来替代null

下面是一个修改后的示例代码:

using System.IO;
using Windows.Storage;

// ...

StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile imageFile = await localFolder.GetFileAsync("_Course/Image/" + Img_str + ".jpg");

if (imageFile != null)
{
    using (IRandomAccessStream fileStream = await imageFile.OpenAsync(FileAccessMode.Read))
    {
        bi.SetSource(fileStream);
    }
}
else
{
    // 图片文件不存在时,创建一个空的 MemoryStream
    using (var emptyStream = new MemoryStream())
    {
        bi.SetSource(emptyStream.AsRandomAccessStream());
    }
}

这段代码首先尝试从本地存储文件夹中获取指定的图片文件。如果文件存在,就直接使用该文件的读取流设置到bi.SetSource()。如果文件不存在(即imageFile == null),则创建一个新的MemoryStream对象(默认为空),然后通过AsRandomAccessStream()转换为随机访问流,再传递给bi.SetSource(),以此来处理文件不存在的情况。这样可以避免因为直接传入null而引发的错误。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
问答地址: