Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine URIs

Tags:

I have two Uri objects passed into some code, one is a directory and the other is a filename (or a relative path)

var a = new Uri("file:///C:/Some/Dirs"); var b = new Uri("some.file"); 

when I try and combine them like this:

var c = new Uri(a,b); 

I get

file:///C:/Some/some.file

where I wold expect to get the same effect as with Path.Combine (as that is the old code I need to replace):

file:///C:/Some/Dirs/some.file

I can't think of a clean solution to this.

The ugly solution being to add a / to the Uri if it's not there

string s = a.OriginalString; if(s[s.Length-1] != '/')    a = new Uri(s + "/"); 
like image 547
BCS Avatar asked May 19 '09 22:05

BCS


Video Answer


2 Answers

This should do the trick for you:

var baseUri = new Uri("http://www.briankeating.net"); var absoluteUri = new Uri(baseUri, "/api/GetDefinitions"); 

This constructor follow the standard relative URI rules so the / are important :

  • http://example.net + foo = http://example.net/foo
  • http://example.net/foo/bar + baz = http://example.net/foo/baz
  • http://example.net/foo/ + bar = http://example.net/foo/bar
  • http://example.net/foo + bar = http://example.net/bar
  • http://example.net/foo/bar/ + /baz = http://example.net/baz
like image 171
brianbruff Avatar answered Oct 07 '22 12:10

brianbruff


Well, you're going to have to tell the Uri somehow that the last part is a directory rather than a file. Using a trailing slash seems to be the most obvious way to me.

Bear in mind that for many Uris, the answer you've got is exactly right. For example, if your web browser is rendering

http://foo.com/bar/index.html 

and it sees a relatively link of "other.html" it then goes to

http://foo.com/bar/other.html 

not

http://foo.com/bar/index.html/other.html 

Using a trailing slash on "directory" Uris is a pretty familiar way of suggesting that relative Uris should just append instead of replacing.

like image 28
Jon Skeet Avatar answered Oct 07 '22 10:10

Jon Skeet