如何在OneDrive映像呈现file.OpenAsync错误时捕获错误

时间:2015-03-21 08:19:03

标签: image error-handling

在项目中,我尝试为用户提供从个人库中选择图像的选项。没有什么特别之处。

当用户从本地图像库中选择所需图像时,这是完美的。但是,当从OneDrive中选择图像时,会发生错误,并且我无法捕获错误。错误的来源似乎在file.OpenAsync方法中。

似乎可能与所选图像的大小存在关系,但我无法分辨,因为我无法捕捉错误。

这里是codesnippet(事实上它取自XAML图像SDK样本)

        Dim picker As New FileOpenPicker With {.ViewMode = PickerViewMode.Thumbnail, .SuggestedStartLocation = PickerLocationId.PicturesLibrary}
        'picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary
        picker.FileTypeFilter.Add(".png")
        picker.FileTypeFilter.Add(".jpeg")
        picker.FileTypeFilter.Add(".jpg")
        picker.FileTypeFilter.Add(".bmp")

        Dim wBitMap as new WritableBitmap(200,200)
        Dim file As StorageFile = Await picker.PickSingleFileAsync()

        ' Ensure a file was selected
        If file IsNot Nothing Then
            Try   ' Set the source of the WriteableBitmap to the image stream
                Using fileStream As IRandomAccessStream = Await file.OpenAsync(Windows.Storage.FileAccessMode.Read)

                    Await wBitmap.SetSourceAsync(fileStream)
                    wBitmap.Invalidate()
                    vwImage.Source = wBitmap
                End Using
                Catch e1 As TaskCanceledException
                ' The async action to set the WriteableBitmap's source may be canceled if the user clicks the button repeatedly


            End Try
        End If

正如你所看到的,有一个try-catch,但是仍然会弹出一个非陷阱错误,然后单步执行,我可以检测到它发生在行中

Await file.OpenAsync(Windows.Storage.FileAccessMode.Read)

现在我的问题是:如何捕获此错误?我是对的,上面的行是错误的来源吗?如果不是这样的话:什么是如何克服?

1 个答案:

答案 0 :(得分:1)

经过大量的实验,我想我找到了解决方案。

当选择StorgeFile作为图像的来源时,最好检查StorageFile.Attributes

选定的文件将带有属性值。对于OneDrive中的文件,Attributes值为544(组合Archive和LocallyIncomplete时得到的值。因此必须首先下载该文件,然后才能使用。

这里解释如下: Link to the MSDN documentation on StorageFile.Attributes