Silverlight / C # image not found exception handling

I am trying to handle the case where the image I'm looking for does not exist - it should have a stack image by default.

i.e.: - when sampleimage = http://www.google.com/images/logos/ps_logo2.png (exists - it should be returned in order) - when sampleimage = http://www.thisimagedoesnotexist.com/something .png (does not exist - it should fall into the catch block)

Below is my code that I use, however it never gets into the catch block when the image does not exist. I use this in a Silverlight application. Any suggestions on how I can make this work?

try
            {
                image.Source = new BitmapImage(new Uri(sampleimage, UriKind.Absolute));
            }
            catch (OutOfMemoryException)
            {
                sampleimage  = "defaulticon.jpg";
                image.Source = new BitmapImage(new Uri(sampleimage, UriKind.Absolute));
            }  
+3
3

URL

        Image image = new Image();
        string sampleimage = "http://www.google.com/images/logos/ps_logo2.png";

        Uri address;

        if (TryGetUriAddress(out address, sampleimage))
        {
            image.Source = new BitmapImage(address);

        }
        else
        {
            sampleimage = "defaulticon.jpg";
            image.Source = new BitmapImage(new Uri(sampleimage, UriKind.Absolute));
        }



 private bool TryGetUriAddress(out Uri validAddress,string addressToCreate)
    {
        bool isValid = false;
        validAddress = null;
        try
        {

            WebClient sc = new WebClient();
            sc.DownloadData(addressToCreate);
            validAddress = new Uri(addressToCreate, UriKind.Absolute);
            isValid = true;
        }
        catch (Exception ex)
        {
            isValid = false;
        }

        return isValid;
    }
+3

, Saurabh . . BitmapImage URI, BitmapImage.

Uri sampleURI;
try{
 sampleURI = new Uri(sampleUriPath,UriKind.Absolute);
}catch(UriFormatException ufex)
{
 sampleURI = new Uri(defaultUriPath,UriKind.Absolute);
}
image.Source = new BitmapImage(sampleURI);
+1

The proper way to handle this is to use the event ImageFailed: -

bool defaultAssigned = false;
Image image = new Image();
image.ImageFailed += (s, args) =>
{
   if (!defaultAssigned)
   {
       image.Source = new BitmapImage(defaultImageUri);
       bDefaultAssigned = true;
   }
}
image.Source = new BitmapImage(sampleImageUri);
+1
source

Source: https://habr.com/ru/post/1777253/


All Articles