C # Equating URI

What is the standard way to determine if these two similar uris are actually the same?

var a = new Uri("http://sample.com/sample/"); var b = new Uri("http://sample.com/sample"); Console.WriteLine(a.Equals(b)); // False 

What is the best way to determine that a == b? I could compare the helper properties of a Uri object such as Host, LocalPath, etc., but I wonder if there is a better way.

Edit: Thanks everyone. I just want the user to do the same or not.

+4
source share
3 answers

The Uri class overrides Equals and implements the == operator to determine equality.

Verification method if two instances of Uri are equivalent:

 if(a == b) 

In your case they are not equivalent. The directory terminator at the end of a has a specific meaning, while b can be a directory or file.

+6
source

As everyone commented - these URLs do not match.

If you have a specific way to compare Urls for your case, you need to write your own code for comparison. Try using the Uri / UriBuilder classes to parse Url in components instead of writing your own when comparing Urls. That is, you might want your comparison to make case-insensitive query string comparisons.

If you want to say that β€œURLs are equal when they point to the same content”, you have a much more interesting problem.

+1
source

If you want to implement your own logic in which the two examples above will be considered the same (I deliberately avoid the term equal for obvious reasons), one solution would be to create an extension method . For instance.

 public static class ExtensionMethods { public static bool AreTheSame(this Uri left, Uri uri) { //your implemention here } } 

then you can:

 var a = new Uri("http://sample.com/sample/"); var b = new Uri("http://sample.com/sample"); Console.WriteLine(a.AreTheSame(b)); 

And you can use this method in your own IComparer<in T> etc.

0
source

Source: https://habr.com/ru/post/1397098/


All Articles