namespace AIStudio.Tools; /// /// Shared rules for comparing file system paths. /// public static class PathTools { /// /// How to compare file system paths: Windows treats them case-insensitively, Linux and /// macOS do not. There, two files may differ in casing alone. /// public static readonly StringComparison COMPARISON = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; /// /// The comparer matching COMPARISON, for path-keyed lookups. /// public static readonly StringComparer COMPARER = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; /// /// Determines whether a path lies below the given directory. /// /// /// The directory itself does not count as lying below itself. A path which cannot be resolved /// counts as lying elsewhere. /// /// The directory. /// The path to check. /// Whether the path lies below the directory. public static bool IsInsideDirectory(string directory, string path) { try { var fullDirectory = Path.GetFullPath(directory); var directoryPrefix = fullDirectory.EndsWith(Path.DirectorySeparatorChar) ? fullDirectory : fullDirectory + Path.DirectorySeparatorChar; return Path.GetFullPath(path).StartsWith(directoryPrefix, COMPARISON); } catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) { return false; } } }