问题
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?
回答1:
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.
回答2:
I would use HttpWebRequest to get the headers, then check the content type, and that the content length is non-zero.
回答3:
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;
}
}
来源:https://stackoverflow.com/questions/1450528/net-verify-url-is-image