tags:

views:

177

answers:

3

I have a requirement to verify that a user-specified URL is to an image. So really I need a way to determine that a URL string points to a valid image. How can I do this in .NET?

+3  A: 

You can't do that without downloading the file (at least a part of it). Use a WebClient to fetch the URL and try creating a new Bitmap from the returned byte[]. If it was successful, it's really an image. Otherwise, it will throw an exception somewhere in the process.

By the way, you can issue a HEAD request and check the Content-Type header in the response (if it's there). However, this method is not fool-proof. The server can respond with an invalid Content-Type header.

Mehrdad Afshari
This would depend how critical it is that the image is valid. Content type usually works, but some servers don't play nice, and you could get an annoying exception later on. Downloading is indeed the only way you can be certain.
Mike K
+2  A: 

I would use HttpWebRequest to get the headers, then check the content type, and that the content length is non-zero.

Mike K
A: 

Here's what I'm using now. Any critiques?

public class Image
{
    public static bool Verifies(string url)
    {
        if (url == null)
        {
            throw new ArgumentNullException("url");
        }

        Uri address;

        if (!Uri.TryCreate(url, UriKind.Absolute, out address))
        {
            return false;
        }

        using (var downloader = new WebClient())
        {
            try
            {
                var image = new Bitmap(downloader.OpenRead(address));
            }
            catch (Exception ex)
            {
                if (// Couldn't download data
                    ex is WebException ||
                    // Data is not an image
                    ex is ArgumentException)
                {
                    return false;
                }
                else
                {
                    throw;
                }
            }
        }

        return true;
    }
}
Chris
What if the link is actually to a 4.7gb ISO. Do you really want to have to download the whole thing and try and convert to a bitmap to determine whether it is an image? If this was part of a webapp, that could use up all your bandwith in a DoS fairly quickly. I think you should check the content type sent in the response headers as Mike K suggested, or check the file extension. If you really must download, check the content length and make sure you don't download anything ridiculously large.
Dale Halliwell