Validate URLs in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; public class Example { public static bool IsValidUrl(string url) { return Uri.IsWellFormedUriString(url, UriKind.Absolute); } public static void Main() { string url = "https://www.google.com/"; if (IsValidUrl(url)) { Console.WriteLine("Valid URL"); } else { Console.WriteLine("Invalid URL"); } } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; public class Example { public static bool IsValidUrl(string url) { Uri? uriResult; return Uri.TryCreate(url, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps); } public static void Main() { string url = "https://www.google.com/"; if (IsValidUrl(url)) { Console.WriteLine("Valid URL"); } else { Console.WriteLine("Invalid URL"); } } } |
That’s all about validating URLs in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)