StringExtensions.cs 2.3 KB

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