.NET: Verify URL is image

2019-07-19 04:12发布

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?

标签: image url verify
3条回答
我命由我不由天
2楼-- · 2019-07-19 04:36

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;
    }
}
查看更多
地球回转人心会变
3楼-- · 2019-07-19 04:51

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.

查看更多
趁早两清
4楼-- · 2019-07-19 04:54

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

查看更多
登录 后发表回答