gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:09:35 26 4
gpt4 key购买 nike

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

即:-- 当样本图像 = 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com