.NET: check image url

I have a requirement to verify that the URL provided by the user matches the image. So I really need a way to determine if the URL string points to a valid image. How to do it in .NET?

+2
source share
3 answers

Here is what I am using right now. Any criticisms?

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;
    }
}
0
source

You cannot do this without downloading the file (at least part of it). Use WebClientto extract the url and try to create a new one Bitmapfrom the returned one byte[]. If it was successful, it really is an image. Otherwise, it will throw an exception somewhere in the process.

, HEAD Content-Type ( ). . Content-Type.

+3

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

+2
source

All Articles