为什么从一个到另一个工作的相对路径不正确?

Why Get A Relative Path From One To Another Working Not Correct?

伙计们,我试过这个:

当前:\netcoreapp2.1\ResultPath

目标:\netcoreapp2.1\ReportPath\report1

   AssemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

   Uri currentPath = new Uri(AssemblyDirectory + "//ResultPath");
   Uri targetPath = new Uri(reportsSubDir);

   Uri relPath = currentPath.MakeRelativeUri(targetPath);

我得到的结果是

relPath.OriginalString = ReportPath/report1

为什么不是../ReportPath/report1?

现在举例:

如果我有

当前:\netcoreapp2.1\ResultPath\Test

目标:\netcoreapp2.1\ReportPath\report1

我用这种方式得到正确的结果

relPath.OriginalString = ../../ReportPath/report10

谁能解释一下为什么在第一步我的相对路径变得糟糕,但在第二步却很好

如果我想以我的方式使用第一个和第二个示例,知道如何修复它吗?

找到答案添加/到当前路径它看起来像 ::

Uri currentPath = new Uri(AssemblyDirectory + "//ResultPath/");

还需要解释:)

好吧,如果您使用的是 .NET 5,那么您很幸运,因为包含了新方法:Path.GetRelativePath(string, string)

如果没有,我们可以随时深入研究 MS .NET Framework 代码:

https://referencesource.microsoft.com/#System.Workflow.ComponentModel/AuthoringOM/Design/DesignerHelpers.cs,a561eb779ce7163d

并复制实现,即:

static class PathHelper
 {
     internal static string GetRelativePath(string pathFrom, string pathTo)
     {
         Uri uri = new Uri(pathFrom);
         string relativePath = Uri.UnescapeDataString(uri.MakeRelativeUri(new Uri(pathTo)).ToString());
         relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
         if (!relativePath.Contains(Path.DirectorySeparatorChar.ToString()))
             relativePath = "." + Path.DirectorySeparatorChar + relativePath;
         return relativePath;
     }
 }

用法为:

var p1 = @"C:\users\turek\source\";
var p2 = @"C:\users\turek\desktop\";

PathHelper.GetRelativePath(p1, p2);
// returns "..\desktop\"