如果WPF图像源链接不存在,则不会出错

时间:2012-06-03 12:25:42

标签: c# wpf image hyperlink

我使用此代码将链接设置为WPF图像源:

bi3.BeginInit();
bi3.UriSource = new Uri("[here is a link]" + textBox2.Text + ".png", UriKind.RelativeOrAbsolute);
bi3.CacheOption = BitmapCacheOption.OnLoad;
bi3.EndInit();

我怎么知道图像的链接是否存在?提前谢谢!

1 个答案:

答案 0 :(得分:3)

private static bool UriExit(Uri uri)
{
    try
    {
        var request = WebRequest.Create(uri) as HttpWebRequest;
        request.Method = "HEAD";
        var response = request.GetResponse() as HttpWebResponse;
        return (response.StatusCode == HttpStatusCode.OK);
    }
    catch
    {
        return false;
    }
}

将其命名为

bool val = UriExit(bi3.UriSource);