StringExtensions.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. namespace GodotTools.Core
  5. {
  6. public static class StringExtensions
  7. {
  8. public static string RelativeToPath(this string path, string dir)
  9. {
  10. // Make sure the directory ends with a path separator
  11. dir = Path.Combine(dir, " ").TrimEnd();
  12. if (Path.DirectorySeparatorChar == '\\')
  13. dir = dir.Replace("/", "\\") + "\\";
  14. var fullPath = new Uri(Path.GetFullPath(path), UriKind.Absolute);
  15. var relRoot = new Uri(Path.GetFullPath(dir), UriKind.Absolute);
  16. // MakeRelativeUri converts spaces to %20, hence why we need UnescapeDataString
  17. return Uri.UnescapeDataString(relRoot.MakeRelativeUri(fullPath).ToString());
  18. }
  19. public static string NormalizePath(this string path)
  20. {
  21. if (string.IsNullOrEmpty(path))
  22. return path;
  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. return rooted ? Path.DirectorySeparatorChar + path : path;
  29. }
  30. private static readonly string DriveRoot = Path.GetPathRoot(Environment.CurrentDirectory);
  31. public static bool IsAbsolutePath(this string path)
  32. {
  33. return path.StartsWith("/", StringComparison.Ordinal) ||
  34. path.StartsWith("\\", StringComparison.Ordinal) ||
  35. path.StartsWith(DriveRoot, StringComparison.Ordinal);
  36. }
  37. public static string ToSafeDirName(this string dirName, bool allowDirSeparator = false)
  38. {
  39. var invalidChars = new List<string> { ":", "*", "?", "\"", "<", ">", "|" };
  40. if (allowDirSeparator)
  41. {
  42. // Directory separators are allowed, but disallow ".." to avoid going up the filesystem
  43. invalidChars.Add("..");
  44. }
  45. else
  46. {
  47. invalidChars.Add("/");
  48. }
  49. string safeDirName = dirName.Replace("\\", "/").Trim();
  50. foreach (string invalidChar in invalidChars)
  51. safeDirName = safeDirName.Replace(invalidChar, "-");
  52. return safeDirName;
  53. }
  54. }
  55. }