In one of the previous posts it was suggested to use System.Uri to check if the URL is valid. How does one do that?
try
{
System.Uri test = new System.Uri(stringToTest);
}
catch (FormatException ex)
{
return false;
}
return true;
If you are checking to see if the structure of the URL is valid, then the previous answer is just fine.
However, if you want to check that the resource actually exists, you are going to have to use the classes that derive from WebRequest/WebResponse. For HTTP and FTP resources, the HttpWebRequest/FtpWebRequest and HttpWebResponse/FtpWebResponse classes will work fine (as will WebClient), but if you have other schemes that you have to support, you will have to find specific providers for that scheme.
To check if an url is valid instead of using exceptions you can use the TryCreate method:
Uri result;
if (Uri.TryCreate("http://www.google.com", UriKind.RelativeOrAbsolute, out result))
{
// the url is valid
}
Can use the static IsWellFormedUriString method:
bool isValid = Uri.IsWellFormedUriString(url, UriKind.Absolute);
http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx
Using Uri.TryCreate can have some problems with relative Uris, with string like this "/folder/{ht.com.m\/sx.r:erp://" TryCreate returns true, so i create this extension method using IsWellFormedUriString and TyrCreate, I'm not sure TryCreate is necessary, with my little tests i get the same results with or without 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);
}
Example
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
}