StringExtensions.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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.ToString() + 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 CsvEscape(this string value, char delimiter = ',')
  34. {
  35. bool hasSpecialChar = value.IndexOfAny(new char[] {'\"', '\n', '\r', delimiter}) != -1;
  36. if (hasSpecialChar)
  37. return "\"" + value.Replace("\"", "\"\"") + "\"";
  38. return value;
  39. }
  40. public static string ToSafeDirName(this string dirName, bool allowDirSeparator)
  41. {
  42. var invalidChars = new List<string> {":", "*", "?", "\"", "<", ">", "|"};
  43. if (allowDirSeparator)
  44. {
  45. // Directory separators are allowed, but disallow ".." to avoid going up the filesystem
  46. invalidChars.Add("..");
  47. }
  48. else
  49. {
  50. invalidChars.Add("/");
  51. }
  52. string safeDirName = dirName.Replace("\\", "/").Trim();
  53. foreach (string invalidChar in invalidChars)
  54. safeDirName = safeDirName.Replace(invalidChar, "-");
  55. return safeDirName;
  56. }
  57. }
  58. }