This post will discuss how to validate URLs in C#.

A simple solution is to use regular expressions to check for a valid URL. This post covers methods that don’t involve using any regex, are safe, and perform comparatively faster.

1. Using Uri.IsWellFormedUriString() method

The Uri.IsWellFormedUriString() method returns true if the specified string is well-formed; otherwise, false. It attempts to construct a URI with the specified string and ensures that it does not require further escaping. For more information on this method, see the official documentation of the Uri.IsWellFormedUriString() method. The following example illustrates.

Download  Run Code

2. Using Uri.TryCreate() method

The Uri.TryCreate() method attempts to create a new Uri using the specified string and a UriKind. It returns true if the Uri was successfully created, and false otherwise. It also takes Uri as out parameter, which will contain the constructed Uri. This can be used to restrict the Uri for HTTP and HTTPS Protocol only, as shown below:

Download  Run Code

That’s all about validating URLs in C#.