2

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?

4

3 回答 3

3

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.

于 2009-09-20T07:37:45.143 回答
2

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

于 2009-09-20T07:38:52.910 回答
0

这是我现在正在使用的。有什么批评吗?

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;
    }
}
于 2009-09-25T04:51:39.110 回答