Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would one use System.Uri .NET class to check if the URL is valid?

Tags:

.net

regex

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?

like image 256
dev.e.loper Avatar asked Mar 31 '09 17:03

dev.e.loper


People also ask

How check URL is valid or not in C#?

To check if a Url is valid in C# you can use Uri. TryCreate() method which creates a new Uri and it does not throw an exception if the Uri cannot be created, it will return a bool if it was created successfully.

Why use URI instead of string?

Uri instead of string to build URLs. A string representation of a URI is prone to parsing and encoding errors and can lead to security vulnerabilities. The Uri class provides these services in a safe and secure manner.

What is URI in VB net?

A URI is a compact representation of a resource available to your application on the intranet or internet. The Uri class defines the properties and methods for handling URIs, including parsing, comparing, and combining. The Uri class properties are read-only; to create a modifiable object, use the UriBuilder class.


1 Answers

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
}
like image 143
Darin Dimitrov Avatar answered Sep 21 '22 14:09

Darin Dimitrov