in src/Sarif.Viewer.VisualStudio.Core/SdkUiUtilities.cs [433:491]
internal static string GetRelativePath(string fromDirectory, string toPath)
{
// Both paths need to be rooted to calculate a relative path
if (!Path.IsPathRooted(fromDirectory) ||
!Path.IsPathRooted(toPath))
{
return toPath;
}
// If toPath is on a different drive then there is no relative path
if (!string.Equals(Path.GetPathRoot(fromDirectory),
Path.GetPathRoot(toPath),
StringComparison.OrdinalIgnoreCase))
{
return toPath;
}
// Get the canonical path. This resolves directory names like "\.\" and "\..\".
fromDirectory = Path.GetFullPath(fromDirectory);
toPath = Path.GetFullPath(toPath);
string[] fromDirectories = fromDirectory.Split(s_directorySeparatorArray, StringSplitOptions.RemoveEmptyEntries);
string[] toDirectories = toPath.Split(s_directorySeparatorArray, StringSplitOptions.RemoveEmptyEntries);
int length = Math.Min(fromDirectories.Length, toDirectories.Length);
// We know at least the drive letter matches so start at index 1
int firstDifference = 1;
// Find the common root
for (; firstDifference < length; firstDifference++)
{
if (!string.Equals(fromDirectories[firstDifference],
toDirectories[firstDifference],
StringComparison.OrdinalIgnoreCase))
{
break;
}
}
var relativePath = new StringCollection();
// Add relative paths to get from fromDirectory to the common root
for (int i = firstDifference; i < fromDirectories.Length; i++)
{
relativePath.Add("..");
}
// Add the relative paths from toPath
for (int i = firstDifference; i < toDirectories.Length; i++)
{
relativePath.Add(toDirectories[i]);
}
// Create the relative path
string[] relativeParts = new string[relativePath.Count];
relativePath.CopyTo(relativeParts, 0);
return string.Join(Path.DirectorySeparatorChar.ToString(), relativeParts);
}