Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to compare 2 urls [closed]

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.

like image 951
hegdesachin Avatar asked Aug 20 '13 09:08

hegdesachin


3 Answers

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);
}
like image 55
Patrik Svensson Avatar answered Oct 29 '22 03:10

Patrik Svensson


use the c# URI class to represent your URIs

then use the uri.compare function

like image 22
asafrob Avatar answered Oct 29 '22 03:10

asafrob


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.

like image 23
ZombieSheep Avatar answered Oct 29 '22 03:10

ZombieSheep