StringExtensions.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Runtime.InteropServices;
  5. namespace GodotTools.Core
  6. {
  7. public static class StringExtensions
  8. {
  9. private static readonly string _driveRoot = Path.GetPathRoot(Environment.CurrentDirectory)!;
  10. public static string RelativeToPath(this string path, string dir)
  11. {
  12. // Make sure the directory ends with a path separator
  13. dir = Path.Combine(dir, " ").TrimEnd();
  14. if (Path.DirectorySeparatorChar == '\\')
  15. dir = dir.Replace("/", "\\", StringComparison.Ordinal) + "\\";
  16. var fullPath = new Uri(Path.GetFullPath(path), UriKind.Absolute);
  17. var relRoot = new Uri(Path.GetFullPath(dir), UriKind.Absolute);
  18. // MakeRelativeUri converts spaces to %20, hence why we need UnescapeDataString
  19. return Uri.UnescapeDataString(relRoot.MakeRelativeUri(fullPath).ToString());
  20. }
  21. public static string NormalizePath(this string path)
  22. {
  23. bool rooted = path.IsAbsolutePath();
  24. path = path.Replace('\\', '/');
  25. path = path[path.Length - 1] == '/' ? path.Substring(0, path.Length - 1) : path;
  26. string[] parts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
  27. path = string.Join(Path.DirectorySeparatorChar.ToString(), parts).Trim();
  28. if (!rooted)
  29. return path;
  30. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  31. {
  32. string maybeDrive = parts[0];
  33. if (maybeDrive.Length == 2 && maybeDrive[1] == ':')
  34. return path; // Already has drive letter
  35. }
  36. return Path.DirectorySeparatorChar + path;
  37. }
  38. public static bool IsAbsolutePath(this string path)
  39. {
  40. return path.StartsWith("/", StringComparison.Ordinal) ||
  41. path.StartsWith("\\", StringComparison.Ordinal) ||
  42. path.StartsWith(_driveRoot, StringComparison.Ordinal);
  43. }
  44. }
  45. }