CSharp · Console
using System;
using System.IO;
Test(subPath: "c:/foo/bar", basePath: "c:/foo"); // with direct child (true)
Test(subPath: "c:/foo/bar/qux", basePath: "c:/foo"); // with level 2 child (true)
Test(subPath: "c:/foo", basePath: "c:/foo/bar"); // with args flipped (false)
Test(subPath: "c:/FOO/bar", basePath: "C:/foo"); // different case (result depends on platform)
Test(subPath: @"c:\foo\bar", basePath: @"c:\foo"); // with backslash (true)
Test(subPath: "c:/foo", basePath: "c:"); // drive letter only (true)
Test(subPath: "c:/foo/bar", basePath: "c:/foo/"); // trailing slash is ignored (true)
Test(subPath: "c:/foo/bar/", basePath: "c:/foo"); // trailing slash is ignored (true)
Test(subPath: "c:/foo/bar", basePath: "c:/foo/bar"); // same path (false)
Test(subPath: "d:/foo/bar", basePath: "c:/foo"); // different root (false)
Test(subPath: "c:/foo/.bar", basePath: "c:/foo"); // foldername starts with a dot (true)
Test(subPath: "c:/foo/../foo/bar", basePath: "c:/foo"); // you're breaking my balls here... (still works, though)
void Test(string subPath, string basePath) {
var isSubPath = subPath.IsSubPathOf(basePath);
var infix = isSubPath ? " " : " NOT ";
Console.WriteLine($"'{subPath}'\tis{infix}a sub path of\t'{basePath}'");
}
public static class Ext {
public static bool IsSubPathOf(this string subPath, string basePath) {
var rel = Path.GetRelativePath(basePath.Replace('\\', '/'), subPath.Replace('\\', '/'));
//Console.WriteLine($"\r\n{rel}\t"); // for debugging
return rel != "."
&& rel != ".."
&& !rel.StartsWith("../")
&& !Path.IsPathRooted(rel);
}
}