StringExtensions.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. Uri fullPath = new Uri(Path.GetFullPath(path), UriKind.Absolute);
  15. Uri relRoot = new Uri(Path.GetFullPath(dir), UriKind.Absolute);
  16. return relRoot.MakeRelativeUri(fullPath).ToString();
  17. }
  18. public static string NormalizePath(this string path)
  19. {
  20. bool rooted = path.IsAbsolutePath();
  21. path = path.Replace('\\', '/');
  22. string[] parts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
  23. path = string.Join(Path.DirectorySeparatorChar.ToString(), parts).Trim();
  24. return rooted ? Path.DirectorySeparatorChar + path : path;
  25. }
  26. private static readonly string DriveRoot = Path.GetPathRoot(Environment.CurrentDirectory);
  27. public static bool IsAbsolutePath(this string path)
  28. {
  29. return path.StartsWith("/", StringComparison.Ordinal) ||
  30. path.StartsWith("\\", StringComparison.Ordinal) ||
  31. path.StartsWith(DriveRoot, StringComparison.Ordinal);
  32. }
  33. public static string ToSafeDirName(this string dirName, bool allowDirSeparator)
  34. {
  35. var invalidChars = new List<string> { ":", "*", "?", "\"", "<", ">", "|" };
  36. if (allowDirSeparator)
  37. {
  38. // Directory separators are allowed, but disallow ".." to avoid going up the filesystem
  39. invalidChars.Add("..");
  40. }
  41. else
  42. {
  43. invalidChars.Add("/");
  44. }
  45. string safeDirName = dirName.Replace("\\", "/").Trim();
  46. foreach (string invalidChar in invalidChars)
  47. safeDirName = safeDirName.Replace(invalidChar, "-");
  48. return safeDirName;
  49. }
  50. }
  51. }