20

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.

Kurubaran
  • 8,696
  • 5
  • 43
  • 65
hegdesachin
  • 285
  • 1
  • 2
  • 9
  • I did a google search. But was not able to find a good way of doing it – hegdesachin Aug 20 '13 at 09:06
  • @hegdesachin You must be the first person to try and compare Urls. No good ways on Google, except the first result: [link](http://msdn.microsoft.com/en-us/library/system.uri.compare.aspx) – Artless Aug 20 '13 at 09:08
  • by the sounds of it `"a".Contains("b")` is enough – Sayse Aug 20 '13 at 09:14

4 Answers4

43

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);
}
Patrik Svensson
  • 13,536
  • 8
  • 56
  • 77
  • what about " http: //www .example.com " with " http: // example.com "? these should be same URI? Note: I added white space other wise stackoverflow thinks these are links. – Meric Ozcan Jan 10 '23 at 16:28
11

use the c# URI class to represent your URIs

then use the uri.compare function

asafrob
  • 1,838
  • 13
  • 16
1

It's difficult to know what you actually mean by "match" here, since you only gave one example. In this case you could do something like this.

bool UrlsMatch(string first, string second)
{
    return !(first.ToLower().StartsWith("http://")) && first.ToLower().StartsWith(second.ToLower());
}

although you may also want to check them the other way around as well.

You could also use Uri.Compare, but without knowing your exact requirements for equality it would be tricky to know if it is completely suitable or not.

ZombieSheep
  • 29,603
  • 12
  • 67
  • 114
0

if i understand what you are trying to accomplish then a function to do this can be something like this

bool Compare(string url1, string url2)
    {
        var str1 = url1.Replace("http://", String.Empty).ToLower();
        var str2 = url2.Replace("http://", String.Empty).ToLower();

        return (str1.Contains(str2) || str2.Contains(str1));
    }
sevdalone
  • 390
  • 1
  • 9
  • you could just return your if parameter, also `replace` returns a new string and doesn't replace the existing one – Sayse Aug 20 '13 at 09:17