C# 中是否存在一种方法来获取给定两个绝对路径输入的相对路径?

发布于 2024-09-30 20:31:45 字数 217 浏览 0 评论 0原文

C# 中是否存在一种方法来获取给定两个绝对路径输入的相对路径?

也就是说,我有两个输入(以第一个文件夹为基础),例如

c:\temp1\adam\

c:\temp1\jamie\

然后输出将是

..\jamie\

Does there exist a method in C# to get the relative path given two absolute path inputs?

That is I would have two inputs (with the first folder as the base) such as

c:\temp1\adam\

and

c:\temp1\jamie\

Then the output would be

..\jamie\

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

绅刃 2024-10-07 20:31:45

不确定是否有更好的方法,但这可行:

var file1 = @"c:\temp1\adam\";
var file2 = @"c:\temp1\jamie\";

var result = new Uri(file1)
    .MakeRelativeUri(new Uri(file2))
    .ToString()
    .Replace("/", "\\");

Not sure if there is a better way, but this will work:

var file1 = @"c:\temp1\adam\";
var file2 = @"c:\temp1\jamie\";

var result = new Uri(file1)
    .MakeRelativeUri(new Uri(file2))
    .ToString()
    .Replace("/", "\\");
删除会话 2024-10-07 20:31:45

这很简单。步骤:

  1. 删除字符串的公共开头 (c:\temp1\)
  2. 计算第一个路径的目录数量(在您的情况下为 1)
  3. 将它们替换为 ..
  4. 添加第二个路径

this is simple. Steps:

  1. Remove common beginning of string (c:\temp1\)
  2. Count number of directories of first path (1 in your case)
  3. Replace them with ..
  4. Add second path
雪花飘飘的天空 2024-10-07 20:31:45

更新:由于构造函数现在已过时,您可以使用:

Uri.UnescapeDataString(new Uri(file1).MakeRelativeUri(new Uri(file2)).ToString())
  .Replace("/", "\\");

旧版本:

Kirk Woll 的想法很好,但您需要通过告诉 Uri 不要转义您的路径来确保您的路径不会被破坏(例如,空格被 %20 替换):

var result = new Uri(file1, true)
    .MakeRelativeUri(new Uri(file2, true))
    .ToString()
    .Replace("/", "\\");

Updated: since the constructor is now obsolete you can use:

Uri.UnescapeDataString(new Uri(file1).MakeRelativeUri(new Uri(file2)).ToString())
  .Replace("/", "\\");

old version:

Kirk Woll's idea is good but you need to ensure your path doesn't get mangled (e.g. spaces replaced by %20) by telling Uri not to escape your path:

var result = new Uri(file1, true)
    .MakeRelativeUri(new Uri(file2, true))
    .ToString()
    .Replace("/", "\\");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文