Recognize .NET MAUI Image loading failure

Frank16384 20 Reputation points

I'm using the .NET MAUI Image control to display images stored on disk.

In rare cases an image file can be damaged, so the image cannot be loaded into the Image control. If this happens, I see an exception in the log:

Microsoft.Maui.FileImageSourceService: Warning: Unable to load image file '/Users/frank/Library/c12d2fe8-90bb-4a19-9887-6091059ea74d-2023-02-20T10-44-41-855Z'. System.InvalidOperationException: Unable to load image file. at Microsoft.Maui.FileImageSourceService.GetImageAsync(IFileImageSource imageSource, Single scale, CancellationToken cancellationToken)

I would like to display a special warning symbol if loading fails.

How can I catch this exception or get to know in any other way, if loading has succeeded or failed?

A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,978 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 37,111 Reputation points Microsoft Vendor


    You could use the GetPlatformImageAsync method and determine whether the returned result is empty to determine whether the image is loaded successfully, please refer to the following code example:

    <Image x:Name="img"
    private async void Image_Loaded(object sender, EventArgs e)
        var res = await img.Source.GetPlatformImageAsync(Handler.MauiContext);
        if (res == null)
            img.Source = "dotnet_bot.png";

    Best Regards,

    Alec Liu.

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful