StringExtensions.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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("/", "\\") + "\\";
  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. if (string.IsNullOrEmpty(path))
  24. return path;
  25. bool rooted = path.IsAbsolutePath();
  26. path = path.Replace('\\', '/');
  27. path = path[path.Length - 1] == '/' ? path.Substring(0, path.Length - 1) : path;
  28. string[] parts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
  29. path = string.Join(Path.DirectorySeparatorChar.ToString(), parts).Trim();
  30. if (!rooted)
  31. return path;
  32. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  33. {
  34. string maybeDrive = parts[0];
  35. if (maybeDrive.Length == 2 && maybeDrive[1] == ':')
  36. return path; // Already has drive letter
  37. }
  38. return Path.DirectorySeparatorChar + path;
  39. }
  40. public static bool IsAbsolutePath(this string path)
  41. {
  42. return path.StartsWith("/", StringComparison.Ordinal) ||
  43. path.StartsWith("\\", StringComparison.Ordinal) ||
  44. path.StartsWith(_driveRoot, StringComparison.Ordinal);
  45. }
  46. }
  47. }