Dar*_*rov 32
要检查url是否有效而不是使用异常,可以使用TryCreate方法:
Uri result;
if (Uri.TryCreate("http://www.google.com", UriKind.RelativeOrAbsolute, out result))
{
// the url is valid
}
Run Code Online (Sandbox Code Playgroud)
Jua*_*dio 13
使用Uri.TryCreate可能有一些问题相对URI,像这样"/folder/{ht.com.m\/sx.r:erp://" TryCreate返回true字符串,所以我创建一个使用IsWellFormedUriString这种扩展方法和TyrCreate,我不确定TryCreate是否必要,我的小测试无论是否有TryCreate我都会得到相同的结果
public static bool IsUri(this string source) {
if(!string.IsNullOrEmpty(source) && Uri.IsWellFormedUriString(source, UriKind.RelativeOrAbsolute)){
Uri tempValue;
return (Uri.TryCreate(source, UriKind.RelativeOrAbsolute, out tempValue));
}
return (false);
}
Run Code Online (Sandbox Code Playgroud)
例
address= "http://www.c$nbv.gob.mx"
if(address.IsUri()){
//returns false
}
address= "http://www.cnbv.gob.mx"
if(address.IsUri()){
//returns true
}
address= "http://www.cnbv.gob.mx:80"
if(address.IsUri()){
//returns true
}
address= "/directory/path"
if(address.IsUri()){
//returns true
}
address= "~re#l|ativ[ainco#recta\car:.\peta"
if(address.IsUri()){
//returns false
}
Run Code Online (Sandbox Code Playgroud)
可以使用静态IsWellFormedUriString方法:
bool isValid = Uri.IsWellFormedUriString(url, UriKind.Absolute);
Run Code Online (Sandbox Code Playgroud)
http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx