0

我有以下代码处理下载图像并将其保存到手机的媒体库。它失败了System.UnauthorizedAccessException,好像有一些跨线程访问。据我了解,await 语句下方的所有代码都在 UI 线程上运行,因此这应该不是问题。此外,我尝试使用以下代码包装var stream = await client.OpenReadTaskAsync(this.Url);Deployment.Current.Dispatcher.BeginInvoke但没有帮助。:( 我在 WP8 上运行它,目的是稍后将代码移植到 WP7。

    private async void OnSaveImageCommand()
    {
        RunProgressIndicator(true, "Downloading image...");
        var client = new WebClient();
        try
        {
            var stream = await client.OpenReadTaskAsync(this.Url); 

            var bitmap = new BitmapImage();
            bitmap.SetSource(stream);

            using (var memoryStream = new MemoryStream())
            {
                var writeableBitmap = new WriteableBitmap(bitmap);
                writeableBitmap.SaveJpeg(memoryStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0,
                                         100);
                memoryStream.SetLength(memoryStream.Position);
                memoryStream.Seek(0, SeekOrigin.Begin);

                var mediaLibrary = new MediaLibrary(); 
                mediaLibrary.SavePicture("image.jpg", memoryStream);
                MessageBox.Show("Image has been saved to the phone's photo album");
            }
        }
        catch 
        {
            MessageBox.Show("Failed to download image"); 
        }
        finally
        {
            RunProgressIndicator(false);
        }
    }
4

1 回答 1

8

您是否在应用的清单中添加了 ID_CAP_MEDIALIB_PHOTO 功能?

ID_CAP_MEDIALIB_PHOTO

UnauthorizedAccessException 有 99% 的情况是缺少能力。

于 2013-01-17T20:26:30.037 回答