PathEx.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.IO;
  2. namespace BansheeEngine
  3. {
  4. /// <summary>
  5. /// Contains helper methods dealing with file and directory paths, extending the functionality provided by
  6. // System.IO.Path.
  7. /// </summary>
  8. public static class PathEx
  9. {
  10. /// <summary>
  11. /// Checks if two paths are equal.
  12. /// </summary>
  13. /// <param name="a">First path.</param>
  14. /// <param name="b">Second path.</param>
  15. /// <returns>True if both paths point to the same place.</returns>
  16. public static bool Compare(string a, string b)
  17. {
  18. return Path.GetFullPath(a) == Path.GetFullPath(b);
  19. }
  20. /// <summary>
  21. /// Checks if one path is part of an another path.
  22. /// </summary>
  23. /// <param name="path">Path to check if it's part of <paramref name="parent"/>.</param>
  24. /// <param name="parent">Parent that might contain <paramref name="path"/>.</param>
  25. /// <returns>True if <paramref name="parent"/> contains <paramref name="path"/>.</returns>
  26. public static bool IsPartOf(string path, string parent)
  27. {
  28. return Path.GetFullPath(path).StartsWith(Path.GetFullPath(parent));
  29. }
  30. /// <summary>
  31. /// Returns the last entry in the path, regardless if that is a directory or a filename.
  32. /// </summary>
  33. /// <param name="path">Path to get the tail of.</param>
  34. /// <returns>Tail of the path. This might be a directory or a filename.</returns>
  35. public static string GetTail(string path)
  36. {
  37. if (string.IsNullOrEmpty(path))
  38. return "";
  39. if (path[path.Length - 1] == Path.DirectorySeparatorChar ||
  40. path[path.Length - 1] == Path.AltDirectorySeparatorChar)
  41. {
  42. return Path.GetDirectoryName(path);
  43. }
  44. return Path.GetFileName(path);
  45. }
  46. /// <summary>
  47. /// Returns the parent of the provided path.
  48. /// </summary>
  49. /// <param name="path">Path to return the parent of.</param>
  50. /// <returns>Parent of the path. This usually means the folder containing the file or folder in the current path.
  51. /// </returns>
  52. public static string GetParent(string path)
  53. {
  54. string tail = GetTail(path);
  55. return path.Remove(path.Length - tail.Length);
  56. }
  57. /// <summary>
  58. /// Checks if the provided name can be used as a file name.
  59. /// </summary>
  60. /// <param name="name">Name to check.</param>
  61. /// <returns>True if the name can be used as a file name.</returns>
  62. public static bool IsValidFileName(string name)
  63. {
  64. return !string.IsNullOrWhiteSpace(name) &&
  65. name.IndexOfAny(Path.GetInvalidFileNameChars()) < 0;
  66. }
  67. }
  68. }