我需要验证用户指定的URL是否适用于图像。所以我真的需要一种方法来确定URL字符串指向有效的图像。我怎么能在.NET中做到这一点?
答案 0 :(得分:3)
如果不下载文件(至少是其中的一部分),则无法做到这一点。使用WebClient
获取网址,然后尝试从返回的Bitmap
创建新的byte[]
。如果它成功了,它真的是一个形象。否则,它将在进程中的某处抛出异常。
顺便说一句,您可以发出HEAD
请求并检查响应中的Content-Type
标头(如果有的话)。但是,这种方法并非万无一失。服务器可以使用无效的Content-Type
标头进行响应。
答案 1 :(得分:2)
我会使用HttpWebRequest获取标题,然后检查内容类型,并且内容长度不为零。
答案 2 :(得分: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;
}
}