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?
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With