Any way to check a url

  • Thread starter Thread starter Henry Jia
  • Start date Start date
H

Henry Jia

Hi,

Does there has any easy way to check if a specified url is a valid one (both the format should be valid but also the specified path / file is available)?

Thanks in advance!

Henry
 
You could always pop the url into a System.Net.WebClient object. If
the url is invalid, or the url is unreachable, the object will throw a
WebException. Of course, this doesn't distinguish between a bad URL
and a bad network connection, for that you would need some additional
tests, perhaps fetching from a known good URL.

HTH,
 
What's the meaning of "pop the url"? and how about the time used for check?

Thank you!

You could always pop the url into a System.Net.WebClient object. If
the url is invalid, or the url is unreachable, the object will throw a
WebException. Of course, this doesn't distinguish between a bad URL
and a bad network connection, for that you would need some additional
tests, perhaps fetching from a known good URL.

HTH,
 
Hi Henry,

So far this method has worked for me, it connects to a DNS server and
checks the name. I strip any http:// headers or folder structures before
passing it to ValidateURL.

// check to see if we can find the url
private bool ValidateURL(string u)
{
try
{
Dns.GetHostByName(u);
}
catch
{
try // maybe we passed an ip address
{
Dns.GetHostByAddress(u);
}
catch
{
return false;
}
}
return true;
}


Happy coding!
Morten Wennevik [C# MVP]
 
Hi Henry,

Sorry for the slang.

Here is a sample:

WebClient wc = new WebClient();
Stream stream = wc.OpenRead("http://www.microsoft.com");
stream.ReadByte();
stream.Close();

If you pass the URL into the OpenRead method, and the code executes
without an exception, then you can be sure that the URL is well formed
and valid, that the server is reachable, and that the path and
filename exist on the server.

As for timing, it won't be as fast as verifying the URL format with a
regular expression, but the only way to be sure you have a valid path
to a file that exists on a remote server is to go to the server and
ask for the file.

HTH,
 
Back
Top