.NET:验证URL是图像 [英] .NET: Verify URL is image
本文介绍了.NET:验证URL是图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要验证用户指定的URL是否为图像。所以我真的需要一种方法来确定URL字符串指向有效的图像。我怎样才能在.NET中执行此操作?
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?
推荐答案
这就是我现在正在使用的内容。任何批评?
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;
}
}
这篇关于.NET:验证URL是图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文