StringExtensions.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. public static string ToSafeDirName(this string dirName, bool allowDirSeparator = false)
  47. {
  48. var invalidChars = new List<string> { ":", "*", "?", "\"", "<", ">", "|" };
  49. if (allowDirSeparator)
  50. {
  51. // Directory separators are allowed, but disallow ".." to avoid going up the filesystem
  52. invalidChars.Add("..");
  53. }
  54. else
  55. {
  56. invalidChars.Add("/");
  57. }
  58. string safeDirName = dirName.Replace("\\", "/").Trim();
  59. foreach (string invalidChar in invalidChars)
  60. safeDirName = safeDirName.Replace(invalidChar, "-");
  61. return safeDirName;
  62. }
  63. }
  64. }