Uredi

Deli z drugimi prek


Path.GetRelativePath(String, String) Method

Definition

Returns a relative path from one path to another.

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

Parameters

relativeTo
String

The source path the result should be relative to. This path is always considered to be a directory.

path
String

The destination path.

Returns

The relative path, or path if the paths don't share the same root.

Exceptions

relativeTo or path is null.

relativeTo or path is effectively empty.

Examples

The following code shows how to call the GetRelativePath method.

// "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

Remarks

Paths are resolved by calling the GetFullPath method before calculating the difference. The method uses the default file path comparison for the current platform (StringComparison.OrdinalIgnoreCase for Windows and MacOs, StringComparison.Ordinal for Linux.

Applies to

See also