How to get the difference between two URIs in C#

Overview

We can get the difference between two instances of a Uri class by using the MakeRelativeUri() method. This method takes two absolute Uri instances and checks if they are the same. If they both have the same base Uri, then the relative Uri of either one will be returned. If they have a different base Uri, then one of them will be returned.

Syntax

uri1.makeRelativeUri(uri2)
Syntax for the MakeRelativeUri() method

Parameters

uri1 and uri2: These are the Uri instances we want to compare.

Return value

A string that is the difference between two Uri instances is returned.

Example

using System;
class HelloWorld
{
static void Main()
{
// Create some Uri instances
Uri address1 = new Uri("https://www.educative.io");
Uri address2 = new Uri("https://www.educative.io/about.html");
Uri address3 = new Uri("https://www.google.com");
Uri address4 = new Uri("https://www.google.com/about.html?greeting=welcome");
// Determine the differences
Console.WriteLine("The difference is {0}", address1.MakeRelativeUri(address2));
Console.WriteLine("The difference is {0}", address1.MakeRelativeUri(address3));
Console.WriteLine("The difference is {0}", address3.MakeRelativeUri(address4));
}
}

Explanation

  • Lines 7–10: We create some Uri instances.
  • Lines 13–15: We get the differences using the MakeRelativeUri() method and print them to the console screen.

Free Resources