tags:

views:

371

answers:

3

It's common knowledge that using System.Diagnostics.Process.Start is the way to launch a url from a C# applicaiton:

System.Diagnostics.Process.Start("http://www.mywebsite.com");

However, if this url is invalid the application seems to have no way of knowing that the call failed or why. Is there a better way to launch a web browser? If not, what is my best option for url validation?

+2  A: 

If you need to verify that the URL exists, the only thing you can do is create a custom request in advance and verify that it works. I'd still use the Process.Start to shell out to the actual page, though.

Danimal
+7  A: 

Try an approach as below.

try
{
    var url = new Uri("http://www.example.com/");

    Process.Start(url.AbsoluteUri);
}
catch (UriFormatException)
{
    // URL is not parsable
}

This does not ensure that the resource exist, but it does ensure the URL is wellformed. You might also want to check if the scheme is matching http or https.

troethom
+1  A: 

Check the Uri.IsWellFormedUriString static method. It's cheaper than catching exception.

derigel
No it isn't but I would use this method for simplicity though. The `Uri.IsWellFormedUriString` calls `Uri.TryCreate` which calls the `Uri.CreateHelper`. This method applies the same technique as my approach and notice that the overheads of multiple methods are introduced.
troethom
@troethom : I never thought it would have such a dumb implementation behind the scenes... wow.
Andrei Rinea