Appending multiple segments with System.Uri

て烟熏妆下的殇ゞ 提交于 2019-12-23 07:26:42

问题


var baseUri = new Uri("http://localhost/");
var uri1 = new Uri(baseUri, "1");
var uri2 = new Uri(uri1, "2");   

Unexpectedly, uri2 is http://localhost/2. How would I append to uri1 so it's http://localhost/1/2 intead? Does Uri do this, or do I need to fallback to strings? Incidentally, I've tried adding leading/trailing slashes almost everywhere.


回答1:


"1" and "2" are "file name portion" of a url. If you make "1" to look more like directory path it will work ok "1/":

var baseUri = new Uri("http://localhost/");
var uri1 = new Uri(baseUri, "1/");
var uri2 = new Uri(uri1, "2"); 

Note: "file name portion" is not a real term, as Url only have "path" and "query" component, but normally last chunk of a path is treated as file name: "/foo/bar/file.txt".

When you combine 2 path you want to replace some tail portion of the first path with the second one. In your case it ends up to have just "file name" segment for both :"/1" and "2" (if you put real value like "/myFile.txt" and "NewFile.txt" in combining it would be easier to see why it behaves this way).



来源:https://stackoverflow.com/questions/10148499/appending-multiple-segments-with-system-uri

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!