Using System.Uri to remove excess slash

I have a condition in my program where I need to combine a server (for example, http://server1.my.corp/ ), which may or may not have a trailing slash with a relative path (for example, /Apps/TestOne/ ). According to the docs , Uri should ...

Canonicalizes the path for hierarchical URIs, compressing sequences such as /. /, / .. /, //, ...

Therefore, when I do something like var url = new Uri(server + relativePath) , I expect it to accept what would otherwise be http://server1.my.corp//Apps/TestOne/ , and remove the double slash (i.e. /// ), but ToString , AbsolutePath , and various options still show the redundant / duplicate slash. I do not use Uri correctly?

+8
c # url
source share
1 answer

Take a look at the constructors for the Uri class . You need to specify the base Uri and relative path to get canonicalized behavior. Try something like this:

 var server = new Uri("http://server1.my.corp/"); var resource = new Uri(server, "/Apps/TestOne/"); 
+15
source share

All Articles