C# 级联url字符串

C# 级联url字符串,c#,string,C#,String,出于这个问题,我正在寻找一种级联url的方法,比如Path.Combine,因为文件系统包含路径参数 我的输入包括以下3个参数: string host = "test.com"; //also possilbe: "test.com/" string path = "/foo/"; //also possilbe: "foo", "/", "","/foo","foo/" string file = "test.temp"; //also possilbe: "/test.temp" 预期的

出于这个问题,我正在寻找一种级联url的方法,比如
Path.Combine
,因为文件系统包含路径参数

我的输入包括以下3个参数:

string host = "test.com"; //also possilbe: "test.com/"
string path = "/foo/"; //also possilbe: "foo", "/", "","/foo","foo/"
string file = "test.temp"; //also possilbe: "/test.temp"
预期的结果是

http://test.com/foo/test.temp

这种方法是我能找到的最好的方法,但并不适用于所有情况:

Uri myUri = new Uri(new Uri("http://" + host +"/"+ path), file);
您可以使用+
IO.Path.Combine
进行以下操作:

如果您想要
Uri
-实例,只需使用
UriBuilder

string url = string.Join("/", new[] { host, path, file }.Select(x => x.Trim('/'))
.Where(x => !String.IsNullOrEmpty(x)));
您可以尝试使用:

如果url的格式不正确,则返回
false
。但是,如果您确定格式正确,则可以使用
Uri
构造函数:

var uri = new Uri(new Uri("http://" + host), path.Trim('/') + "/" + file.Trim('/'));

为什么不在每次合并主机、路径和文件之前都修剪它们呢。然后在组合它们时,使用正斜杠。@singsuyash因为
path
可以为空,所以根据大小写进行修剪如果存在正斜杠,则添加正斜杠(如果不为空),并创建最终的主机、路径和文件。然后像scheme+host+path这样组合它们。@fubo我使用的扩展方法怎么样?@RezaAghaei是的,这很好,在我问这个问题之前,我已经对Ales Potocnik Hahonina的答案投了赞成票,但我更倾向于选择一个较细的liner@fubo:然后删除多余的斜杠。我已经编辑了我的答案,并用你的样本进行了测试。这正是
路径的一部分。Combine
我不明白。它应该自动删除或添加它们,而此代码可能会回答问题,并提供有关此代码回答问题的原因和/或如何提高其长期价值的附加上下文。
Uri uri;
bool success = Uri.TryCreate(new Uri("http://" + host), path.Trim('/') + "/" + file.Trim('/'), out uri);
var uri = new Uri(new Uri("http://" + host), path.Trim('/') + "/" + file.Trim('/'));