How to check if a URI is wrongly or correctly built in C#

Overview

We can check if a URI is correctly or wrongly built using the IsWellFormedOriginalString() method.

Syntax

uri.IsWellFormedOriginalString()
syntax for IsWellFormedOriginalString() method

Parameter

uri: The Uri instance we want to check if it is correctly built.

Return value

A Boolean is returned. If the URI is well-formed, then a true is returned. Otherwise, false is returned.

Code example

Let's look at the code below:

using System;
class UriExample
{
//Entry point of Program
static public void Main()
{
// Create some Uri objects
Uri uri1 = new Uri("https://www.educative.io");
Uri uri2 = new Uri("https://google.com");
Uri uri3 = new Uri("http://maps.google.com/maps?q={!Account.BillingAddress}");
Uri uri4 = new Uri("https://www.hello.124/%%");
// check if they are correctly built
Console.WriteLine(uri1.IsWellFormedOriginalString()); // True
Console.WriteLine(uri2.IsWellFormedOriginalString()); // True
Console.WriteLine(uri3.IsWellFormedOriginalString()); // False
Console.WriteLine(uri4.IsWellFormedOriginalString()); // False
}
}

Explanation

  • Lines 9 to 12: We create some Uri instances.
  • Lines 15 to 18: We check if the Uri instances were built correctly using the IsWellFormedOriginalString() method, and then print the results.

Free Resources