Test to see if an image exists in C#

Solution 1:

Just use HEAD. No need to download the entire image if you don't need it. Here some boilerplate code.

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url");
request.Method = "HEAD";

bool exists;
try
{
    request.GetResponse();
    exists = true;
}
catch
{
   exists = false;
}

Solution 2:

You might want to also check that you got an OK status code (ie HTTP 200) and that the mime type from the response object matches what you're expecting. You could extend that along the lines of,

public bool doesImageExistRemotely(string uriToImage, string mimeType)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriToImage);
    request.Method = "HEAD";

    try
    {
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK && response.ContentType == mimeType)
        {
            return true;
        }
        else
        {
            return false;
        }   
    }
    catch
    {
        return false;
    }
}