Utility.Path.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //------------------------------------------------------------
  2. // Game Framework
  3. // Copyright © 2013-2021 loyalsoft. All rights reserved.
  4. // Homepage: http://www.game7000.com/
  5. // Feedback: http://www.game7000.com/
  6. //------------------------------------------------------------
  7. using System.IO;
  8. namespace GameFramework
  9. {
  10. public static partial class Utility
  11. {
  12. /// <summary>
  13. /// 路径相关的实用函数。
  14. /// </summary>
  15. public static class Path
  16. {
  17. /// <summary>
  18. /// 获取规范的路径。
  19. /// </summary>
  20. /// <param name="path">要规范的路径。</param>
  21. /// <returns>规范的路径。</returns>
  22. public static string GetRegularPath(string path)
  23. {
  24. if (path == null)
  25. {
  26. return null;
  27. }
  28. return path.Replace('\\', '/');
  29. }
  30. /// <summary>
  31. /// 获取远程格式的路径(带有file:// 或 http:// 前缀)。
  32. /// </summary>
  33. /// <param name="path">原始路径。</param>
  34. /// <returns>远程格式路径。</returns>
  35. public static string GetRemotePath(string path)
  36. {
  37. string regularPath = GetRegularPath(path);
  38. if (regularPath == null)
  39. {
  40. return null;
  41. }
  42. return regularPath.Contains("://") ? regularPath : ("file:///" + regularPath).Replace("file:////", "file:///");
  43. }
  44. /// <summary>
  45. /// 移除空文件夹。
  46. /// </summary>
  47. /// <param name="directoryName">要处理的文件夹名称。</param>
  48. /// <returns>是否移除空文件夹成功。</returns>
  49. public static bool RemoveEmptyDirectory(string directoryName)
  50. {
  51. if (string.IsNullOrEmpty(directoryName))
  52. {
  53. throw new GameFrameworkException("Directory name is invalid.");
  54. }
  55. try
  56. {
  57. if (!Directory.Exists(directoryName))
  58. {
  59. return false;
  60. }
  61. // 不使用 SearchOption.AllDirectories,以便于在可能产生异常的环境下删除尽可能多的目录
  62. string[] subDirectoryNames = Directory.GetDirectories(directoryName, "*");
  63. int subDirectoryCount = subDirectoryNames.Length;
  64. foreach (string subDirectoryName in subDirectoryNames)
  65. {
  66. if (RemoveEmptyDirectory(subDirectoryName))
  67. {
  68. subDirectoryCount--;
  69. }
  70. }
  71. if (subDirectoryCount > 0)
  72. {
  73. return false;
  74. }
  75. if (Directory.GetFiles(directoryName, "*").Length > 0)
  76. {
  77. return false;
  78. }
  79. Directory.Delete(directoryName);
  80. return true;
  81. }
  82. catch
  83. {
  84. return false;
  85. }
  86. }
  87. }
  88. }
  89. }