gpt4 book ai didi

c# - 使用 C# 组合两个相对路径

转载 作者:太空宇宙 更新时间:2023-11-03 13:17:07 25 4
gpt4 key购买 nike

“将相对路径附加到绝对路径”有很多骗局,但我需要添加 relative to relative。

例如:

Path1 = "Parent/Child/a.txt"
Path2 = "../Sibling/file.cs"

Result = "Parent/Sibling/file.cs"

尝试过:

  • Directory.GetParent() - 有效,但我找不到返回结果的方法(它只能返回绝对路径)
  • Path.Combine() - 仅适用于简单情况和绝对路径。在相对路径中使用“..”失败(严重!)

...编写一个字符串标记化 Path 类来解决这个问题似乎很荒谬,但我一直在挖掘 MSDN 文档,似乎无法找到一个可以正确处理相对路径的工作路径/目录类.

更糟的是......我正在努力让这项工作一直回到.NET 2(感谢Mono兼容性)

最佳答案

我知道下面的代码很丑陋但是可以工作(抱歉我还没有在单声道上确认):

var Result =
Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Path1), Path2))
.Substring(Directory.GetCurrentDirectory().Length + 1); // +1 to remove leading path separator

关于c# - 使用 C# 组合两个相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25710480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com