1

Possible Duplicate:
How to check that a uri string is valid

I have a text box where user is supposed to enter a URL , How can I programmatically figure out the a URL that user has been entered is valid or not ,If it valid have to process further process else have to enter valid url?

I try this code:

string url = textBox1.Text;
if (!url.StartsWith("http://"))
    url = "http://" + url;
Uri myUri;
if(Uri.TryCreate(url,UriKind.RelativeOrAbsolute,out myUri))
{
    //use the uri here
}
else
{
    MessageBox.Show("Please Enter the Absolute URL name");
    textBox1.Clear();
    textBox1.Focus();
}
Community
  • 1
  • 1
Gan
  • 93
  • 1
  • 3
  • 11
  • 3
    why not `Uri.TryCreate`?? (http://msdn.microsoft.com/en-US/library/system.uri.trycreate.aspx)? or what do you mean by `valid`? reachable (reachable within your vpn, or globally, ...)? or just spec-valid (http://www.w3.org/Addressing/URL/url-spec.txt)? –  Nov 06 '12 at 11:45
  • as you've added some code: and what is the problem? –  Nov 06 '12 at 11:47
  • 2
    Can you be a bit more specific on what you consider to be a 'valid' url? Does it just have to match a pattern or does it have to resolve to a document/page/resource? – KazR Nov 06 '12 at 11:48
  • Use `UriKind.Absolute` for absolute uris. – Paolo Moretti Nov 06 '12 at 11:56

1 Answers1

-1

This answer is from a similar Question A better way to validate URL in C# than try-catch?

string myString="http://someUrl";
Uri myUri;
if(Uri.TryCreate(myString,UriKind.RelativeOrAbsolute,out myUri)
{
    //use the uri here
}
Community
  • 1
  • 1
Ahmad
  • 12,336
  • 6
  • 48
  • 88