从IsolatedStorage加载保存的图像时发生System.InvalidOperationException

时间:2013-01-20 12:12:20

标签: c# wpf windows-phone-7 windows-phone-7.1 windows-phone-8

我在链接ImageCaching找到了一个班级 但是当我从孤立存储加载时,我得到了一个例外" System.InvalidOperationException"

这是我的代码

 public static object DownloadFromWeb(Uri imageFileUri)
    {
        WebClient m_webClient = new WebClient();                                //Load from internet
        BitmapImage bm = new BitmapImage();

        m_webClient.OpenReadCompleted += (o, e) =>
        {
            if (e.Error != null || e.Cancelled) return;
            WriteToIsolatedStorage(IsolatedStorageFile.GetUserStoreForApplication(), e.Result, GetFileNameInIsolatedStorage(imageFileUri));
            bm.SetSource(e.Result);
            e.Result.Close();
        };
        m_webClient.OpenReadAsync(imageFileUri);
        return bm;
    }

    public static object ExtractFromLocalStorage(Uri imageFileUri)
    {
        byte[] data;
        string isolatedStoragePath = GetFileNameInIsolatedStorage(imageFileUri);       //Load from local storage
        if (null == _storage)
        {
             _storage = IsolatedStorageFile.GetUserStoreForApplication();
        }
        using (IsolatedStorageFileStream sourceFile = _storage.OpenFile(isolatedStoragePath, FileMode.Open, FileAccess.Read))
        {


            // Read the entire file and then close it
            sourceFile.Read(data, 0, data.Length);
            sourceFile.Close();
           BitmapImage bm = new BitmapImage();
            bm.SetSource(sourceFile);///here got the exeption 
            return bm;

        }

    }

这样我就无法设置图像。

1 个答案:

答案 0 :(得分:0)

我正在使用您提到的转换器,但它可以修改方法。

您的ExtractFromLocalStorage方法不一样。在关闭流之前,请使用SetSource方法。

以下是原始方法代码:

 private static object ExtractFromLocalStorage(Uri imageFileUri)
    {
        string isolatedStoragePath = GetFileNameInIsolatedStorage(imageFileUri);       //Load from local storage
        using (var sourceFile = _storage.OpenFile(isolatedStoragePath, FileMode.Open, FileAccess.Read))
        {
            BitmapImage bm = new BitmapImage();
            bm.SetSource(sourceFile);
            return bm;
        }
    }
相关问题