diff --git a/src/libraries/System.IO.FileSystem/src/System/IO/DirectoryInfo.cs b/src/libraries/System.IO.FileSystem/src/System/IO/DirectoryInfo.cs index 80a44bd3ad926c..efb432d0a56841 100644 --- a/src/libraries/System.IO.FileSystem/src/System/IO/DirectoryInfo.cs +++ b/src/libraries/System.IO.FileSystem/src/System/IO/DirectoryInfo.cs @@ -74,20 +74,15 @@ public DirectoryInfo CreateSubdirectory(string path) string newPath = Path.GetFullPath(Path.Combine(FullPath, path)); - ReadOnlySpan trimmedNewPath = Path.TrimEndingDirectorySeparator(newPath.AsSpan()); - ReadOnlySpan trimmedCurrentPath = Path.TrimEndingDirectorySeparator(FullPath.AsSpan()); - // We want to make sure the requested directory is actually under the subdirectory. - if (trimmedNewPath.StartsWith(trimmedCurrentPath, PathInternal.StringComparison) - // Allow the exact same path, but prevent allowing "..\FooBar" through when the directory is "Foo" - && ((trimmedNewPath.Length == trimmedCurrentPath.Length) || PathInternal.IsDirectorySeparator(newPath[trimmedCurrentPath.Length]))) - { - FileSystem.CreateDirectory(newPath); - return new DirectoryInfo(newPath); - } - - // We weren't nested - throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, FullPath), nameof(path)); + // Allow the exact same path, but prevent allowing "..\FooBar" through when the directory is "Foo" + string newPathWithTrailingSeparator = PathInternal.EnsureTrailingSeparator(newPath); + string currentPathWithTrailingSeparator = PathInternal.EnsureTrailingSeparator(FullPath); + if (!newPathWithTrailingSeparator.StartsWith(currentPathWithTrailingSeparator, PathInternal.StringComparison)) + throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, newPath, FullPath), nameof(path)); + + FileSystem.CreateDirectory(newPath); + return new DirectoryInfo(newPath); } public void Create()