diff --git a/src/Compilers/Core/CodeAnalysisTest/FileSystem/PathUtilitiesTests.cs b/src/Compilers/Core/CodeAnalysisTest/FileSystem/PathUtilitiesTests.cs index 16ecf206029d7..c660ffa62b568 100644 --- a/src/Compilers/Core/CodeAnalysisTest/FileSystem/PathUtilitiesTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/FileSystem/PathUtilitiesTests.cs @@ -383,5 +383,21 @@ public void CombinePaths_DifferentFromPathCombine(string expected, string path1, { Assert.Equal(expected, PathUtilities.CombinePaths(path1, path2)); } + + [ConditionalFact(typeof(WindowsOnly)), WorkItem(51602, @"https://github.com/dotnet/roslyn/issues/51602")] + public void GetRelativePath_EnsureNo_IndexOutOfRangeException_Windows() + { + var expected = ""; + var result = PathUtilities.GetRelativePath(@"C:\A\B\", @"C:\A\B"); + Assert.Equal(expected, result); + } + + [ConditionalFact(typeof(UnixLikeOnly)), WorkItem(51602, @"https://github.com/dotnet/roslyn/issues/51602")] + public void GetRelativePath_EnsureNo_IndexOutOfRangeException_Unix() + { + var expected = ""; + var result = PathUtilities.GetRelativePath(@"/A/B/", @"/A/B"); + Assert.Equal(expected, result); + } } } diff --git a/src/Compilers/Core/Portable/FileSystem/PathUtilities.cs b/src/Compilers/Core/Portable/FileSystem/PathUtilities.cs index 297dec288f528..b3b7cedccfe78 100644 --- a/src/Compilers/Core/Portable/FileSystem/PathUtilities.cs +++ b/src/Compilers/Core/Portable/FileSystem/PathUtilities.cs @@ -534,6 +534,9 @@ public static string GetRelativePath(string directory, string fullPath) { string relativePath = string.Empty; + directory = TrimTrailingSeparators(directory); + fullPath = TrimTrailingSeparators(fullPath); + if (IsChildPath(directory, fullPath)) { return GetRelativeChildPath(directory, fullPath);