c# - Silverlight/C# 图像未找到异常处理

标签 c# silverlight image exception

我正在尝试处理我要查找的图像不存在的情况 - 它应该默认为股票图标图像。

即: -- 当样本图像 = http://www.google.com/images/logos/ps_logo2.png (存在 - 它应该返回正常) -- 当样本图像 = http://www.thisimagedoesnotexist.com/something.png (不存在 - 它应该进入 catch block )

下面是我正在使用的代码 - 但是当图像不存在时它永远不会进入 catch block 。我在 Silverlight 应用程序中使用它。关于如何让它工作的任何建议?

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

最佳答案

试试下面的代码

添加了处理未找到 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;
    }

关于c# - Silverlight/C# 图像未找到异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4295292/

相关文章:

image - 使用 script-fu gimp 调整图像大小

c# - 多个 cookie 选项 - ASP.NET Identity

c# - 这个令人困惑的表达式 "a == b ? value1 : value2"是什么?

ios - 用户转到主屏幕后,按钮不会更改单击时的图像

c# - 如何将参数发送到 ICommand 的 Execute 方法

c# - 相当于绘图应用程序的橡皮擦、c#、silverlight、wp7

ios - 快速下载 url 并填充 uiimageview

c# - 是否建议为所有 C# 枚举添加后缀 "Enum"以避免命名冲突?

c# - 你能放心地说这个代码是 "unsafe"

c# - MySqlDataReader GetBytes 缓冲区问题...