Path.GetRelativePath(String, String) 方法

定义

返回从一个路径到另一个路径的相对路径。

public:
 static System::String ^ GetRelativePath(System::String ^ relativeTo, System::String ^ path);
public static string GetRelativePath (string relativeTo, string path);
static member GetRelativePath : string * string -> string
Public Shared Function GetRelativePath (relativeTo As String, path As String) As String

参数

relativeTo
String

相对于结果的源路径。 此路径始终被视为目录。

path
String

目标路径。

返回

相对路径,如果路径不共享同一根,则为 path

例外

relativeTopathnull

relativeTopath 实际上为空。

示例

下面的代码演示如何调用 GetRelativePath 方法。

// "C:/Program Files/Microsoft" relative to "C:/Program Files/Common Files" is "../Microsoft"
Console.WriteLine(Path.GetRelativePath("C:/Program Files/Common Files", "C:/Program Files/Microsoft"));
// "C:/Program Files/Microsoft" relative to "C:/Program Files/" is "Microsoft"
Console.WriteLine(Path.GetRelativePath("C:/Program Files/", "C:/Program Files/Microsoft"));

// This code produces output similar to the following:
//
// ../Microsoft
// Microsoft
' "C:/Program Files/Microsoft" relative to "C:/Program Files/Common Files" is "../Microsoft"
Console.WriteLine(Path.GetRelativePath("C:/Program Files/Common Files", "C:/Program Files/Microsoft"))
' "C:/Program Files/Microsoft" relative to "C:/Program Files/" is "Microsoft"
Console.WriteLine(Path.GetRelativePath("C:/Program Files/", "C:/Program Files/Microsoft"))

' This code produces output similar to the following:
'
' ../Microsoft
' Microsoft

注解

在计算差值之前, GetFullPath 通过调用 方法解析路径。 方法使用适用于 Windows 和 MacOs StringComparison.Ordinal 的当前平台的默认文件路径比较 (StringComparison.OrdinalIgnoreCase,适用于 Linux。

适用于

另请参阅