StringExtensions.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.IO;
  3. namespace GodotSharpTools
  4. {
  5. public static class StringExtensions
  6. {
  7. public static string RelativeToPath(this string path, string dir)
  8. {
  9. // Make sure the directory ends with a path separator
  10. dir = Path.Combine(dir, " ").TrimEnd();
  11. if (Path.DirectorySeparatorChar == '\\')
  12. dir = dir.Replace("/", "\\") + "\\";
  13. Uri fullPath = new Uri(Path.GetFullPath(path), UriKind.Absolute);
  14. Uri relRoot = new Uri(Path.GetFullPath(dir), UriKind.Absolute);
  15. return relRoot.MakeRelativeUri(fullPath).ToString();
  16. }
  17. public static string NormalizePath(this string path)
  18. {
  19. bool rooted = path.IsAbsolutePath();
  20. path = path.Replace('\\', '/');
  21. string[] parts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
  22. path = string.Join(Path.DirectorySeparatorChar.ToString(), parts).Trim();
  23. return rooted ? Path.DirectorySeparatorChar.ToString() + path : path;
  24. }
  25. private static readonly string driveRoot = Path.GetPathRoot(Environment.CurrentDirectory);
  26. public static bool IsAbsolutePath(this string path)
  27. {
  28. return path.StartsWith("/", StringComparison.Ordinal) ||
  29. path.StartsWith("\\", StringComparison.Ordinal) ||
  30. path.StartsWith(driveRoot, StringComparison.Ordinal);
  31. }
  32. public static string CsvEscape(this string value, char delimiter = ',')
  33. {
  34. bool hasSpecialChar = value.IndexOfAny(new char[] { '\"', '\n', '\r', delimiter }) != -1;
  35. if (hasSpecialChar)
  36. return "\"" + value.Replace("\"", "\"\"") + "\"";
  37. return value;
  38. }
  39. }
  40. }