如何用C#检查远程图像是否存在

时间:2011-01-21 15:34:10

标签: c#

public void BuildImg()
{
    // The two different images as strings.
    string url1 = "http://remoteimage.com/image.jpg";
    string url2 = "http://remoteimage.com/image2.jpg";

    try
    {
        // Check to see if url1 exists or not
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
        request.Credentials = System.Net.CredentialCache.DefaultCredentials;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        myImg.Visible = true;
        myImg.ImageUrl = url1;
    }
    catch (Exception ex)
    {
        // Check to see if url2exists or not
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url2);
        request.Credentials = System.Net.CredentialCache.DefaultCredentials;
        HttpWebResponse response;
        try
        {
            response = request.GetResponse() as HttpWebResponse;
        }
        catch (WebException exc)
        {
            response = exc.Response as HttpWebResponse;
        }
        // Set myImg to show if url2 exists
        myImg.Visible = true;
        myImg.ImageUrl = url2;

        // If response returns 404, then hide myImg
        if (response.StatusCode == HttpStatusCode.NotFound)
        {
            myImg.Visible = false;
        }

    }

1 个答案:

答案 0 :(得分:1)

var arr = new[]
{
    "http://example.com/image.jpg",
    "http://example.com/image2.jpg"
    ...
};

myImg.ImageUrl = arr.FirstOrDefault(i => CheckExistence(i));

static bool CheckUrlExistence(string url)
{
    try
    {
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Credentials = CredentialCache.DefaultCredentials;
        request.Method = "HEAD";
        var response = (HttpWebResponse)request.GetResponse();
        return response.StatusCode == HttpStatusCode.OK;
    }
    catch (Exception ex)
    {
        var code = ((HttpWebResponse)((WebException)ex).Response).StatusCode; // NotFound, etc
        return false;
    }