Detecting image URL in C#/.NET

You could of course simply check whether the URL ends with a known image file extension. However, a safer method is to actually download the resource and check, whether the content you get actually is an image:

public static bool IsUrlImage(string url)
{
    try
    {
        var request = WebRequest.Create(url);
        request.Timeout = 5000;
        using (var response = request.GetResponse())
        {
            using (var responseStream = response.GetResponseStream())
            {
                if (!response.ContentType.Contains("text/html"))
                {
                    using (var br = new BinaryReader(responseStream))
                    {
                        // e.g. test for a JPEG header here
                        var soi = br.ReadUInt16();  // Start of Image (SOI) marker (FFD8)
                        var jfif = br.ReadUInt16(); // JFIF marker (FFE0)
                        return soi == 0xd8ff && jfif == 0xe0ff;
                    }
                }
            }
        }
    }
    catch (WebException ex)
    {
        Trace.WriteLine(ex);
        throw;
    }
    return false;
}

You can send an HTTP request to the URL (using HttpWebRequest), and check whether the returned ContentType starts with image/.


You can detemine it using the HEAD method of Http (without downloading the whole image)

bool IsImageUrl(string URL)
{
    var req = (HttpWebRequest)HttpWebRequest.Create(URL);
    req.Method = "HEAD";
    using (var resp = req.GetResponse())
    {
        return resp.ContentType.ToLower(CultureInfo.InvariantCulture)
                   .StartsWith("image/");
    }
}

You could just check the string with .EndsWith() for each of a set of strings you define.

If you want to know if the object at that URL is actually an image, you will have to perform the web request yourself and check the content-type HTTP header.

Even that may be inaccurate, however, depending on the server.

Tags:

C#

.Net

Url

C# 4.0