【问题标题】:How to calculate a relative URL to a relative URL in .NET?如何计算 .NET 中相对 URL 的相对 URL?
【发布时间】:2014-10-20 11:31:55
【问题描述】:

我有一个“基本 URL”(它本身是相对的)和一个“子 URL”,它也是相对于“基本 URL”的。我想正确地结合这些。例如:

"some/path/here" + "../other/path" => "some/other/path"

如何在 .NET 中做到这一点? Uri 类要求第一个 Uri 是绝对的。

添加:更多示例,以澄清。

"contents/styles/style.css" + "image.jpg" => "contents/styles/image.jpg"
"contents/folder/style.css" + "../image.jpg" => "contents/image.jpg"
"contents/folder/style.css" + "../images/image.jpg" => "contents/images/image.jpg"

换句话说,在原始示例中,由于here 没有尾部斜杠,因此应将其视为文件。因此,.. 移动到文件夹 some

【问题讨论】:

  • 你的意思是"some/path/here" + "../../other/path" => "some/other/path"
  • @artm - 不。我会举更多例子。
  • 请更好地解释你的例子。这对我来说不是很清楚,我也认为其他人。谢谢。
  • @MSX - 你去吧。
  • @MSX - 嗯,可能还不错。它可以沿着一些分隔符很好地分割,然后我只需要遍历路径并处理...的特殊情况。

标签: c# .net uri


【解决方案1】:

试试:

UriBuilder builder = new UriBuilder();
Uri baseuri = builder.Uri;
builder.Path = "some/path/here";
Uri finalUri = baseuri.MakeRelativeUri(new Uri(builder.Uri, "..\\other\\path"));

Uri finalUri = baseuri.MakeRelativeUri(new Uri(builder.Uri, "file"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 2017-09-21
    • 2013-06-15
    相关资源
    最近更新 更多