我有两个Uri对象传入一些代码,一个是目录,另一个是文件名(或相对路径)
var a = new Uri("file:///C:/Some/Dirs");
var b = new Uri("some.file");
Run Code Online (Sandbox Code Playgroud)
当我尝试将它们组合起来时:
var c = new Uri(a,b);
Run Code Online (Sandbox Code Playgroud)
我明白了
file:///C:/Some/some.file
我希望得到与之相同的效果Path.Combine(因为那是我需要替换的旧代码):
file:///C:/Some/Dirs/some.file
我想不出一个干净的解决方案.
丑陋的解决方案是/在Uri中添加一个,如果不存在的话
string s = a.OriginalString;
if(s[s.Length-1] != '/')
a = new Uri(s + "/");
Run Code Online (Sandbox Code Playgroud)
小智 21
这应该是你的诀窍:
var baseUri = new Uri("http://www.briankeating.net");
var absoluteUri = new Uri(baseUri, "/api/GetDefinitions");
Run Code Online (Sandbox Code Playgroud)
此构造函数遵循标准的相对URI规则,因此/非常重要:
http://example.net+ foo=http://example.net/foohttp://example.net/foo/bar+ baz=http://example.net/foo/bazhttp://example.net/foo/+ bar=http://example.net/foo/barhttp://example.net/foo+ bar=http://example.net/barhttp://example.net/foo/bar/+ /baz=http://example.net/bazJon*_*eet 16
那么,你将不得不告诉乌里不知何故,最后的部分是一个目录,而不是一个文件.使用尾部斜线对我来说似乎是最明显的方式.
请记住,对于许多Uris来说,你得到的答案是完全正确的.例如,如果您的Web浏览器正在呈现
http://foo.com/bar/index.html
Run Code Online (Sandbox Code Playgroud)
然后它会看到"other.html"的相对链接
http://foo.com/bar/other.html
Run Code Online (Sandbox Code Playgroud)
不
http://foo.com/bar/index.html/other.html
Run Code Online (Sandbox Code Playgroud)
在"目录"上使用尾部斜线Uris是一种非常熟悉的方式,表明相对Uris应该只是追加而不是替换.
你可以尝试这种扩展方法!一直工作!;-)
public static class StringExtension
{
public static string UriCombine(this string str, string param)
{
if (!str.EndsWith("/"))
{
str = str + "/";
}
var uri = new Uri(str);
return new Uri(uri, param).AbsoluteUri;
}
}
Run Code Online (Sandbox Code Playgroud)
安吉洛,亚历山德罗