Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

.net - How to combine URIs

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 + "/");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...