用C#组合两个相对路径 [英] Combining two relative paths with C#

查看:92
本文介绍了用C#组合两个相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将相对路径附加到绝对路径"有很多欺骗,但我需要添加相对于相对.

There are many dupes for "appending a relative path to an absolute path", but I need to add relative to relative.

例如:

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

Result = "Parent/Sibling/file.cs"

<小时>

尝试过:


Tried:

  • Directory.GetParent() - 有效,但我找不到返回结果的方法(它只能返回绝对路径)
  • Path.Combine() - 仅适用于简单情况和绝对路径.使用带有相对路径的.."失败(严重!)
  • Directory.GetParent() - works, but I can't find a way to return the result (it can only return absolute paths)
  • Path.Combine() - only works for simple cases and absolute paths. Fails (badly!) on the use of ".." with relative paths

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

...it seems absurd to write a string-tokenizing Path class to solve this, but I've been digging through the MSDN docs and can't seem to find a working Path/Directory class that correctly works with relative paths.

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

To make matters worse ... I'm trying to make this work all the way back to .NET 2 (thanks to Mono compatibilty)

推荐答案

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

I know the following code is ugly but will work (sorry I don't confirm on mono yet):

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

这篇关于用C#组合两个相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆