Best way to compare 2 urls

hegdesachin picture hegdesachin · Aug 20, 2013 · Viewed 11.8k times · Source

I want to compare 2 URLs. Whats the best way to do this?

Conditions: 1) It should exclude the http scheme. 2) 'foo.com/a/b' and 'foo.com/a' should be a match.

Answer

Patrik Svensson picture Patrik Svensson · Aug 20, 2013

You should use the Uri.Compare method.

Here is an example to compare two URI's with different schemes.

public static void Test()
{
    Uri uri1 = new Uri("http://www.foo.com/baz?bar=1");
    Uri uri2 = new Uri("https://www.foo.com/BAZ?bar=1");

    var result = Uri.Compare(uri1, uri2, 
        UriComponents.Host | UriComponents.PathAndQuery, 
        UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase);

    Debug.Assert(result == 0);
}