PathUtils.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. namespace MeloongCore;
  2. public static class PathUtils {
  3. /// <summary>
  4. /// 若路径较长,则尽量将其转换为短路径。
  5. /// 若输入的是文件夹路径,不保证其结尾是否有 \ 。
  6. /// </summary>
  7. public static string Shorten(string fullName, bool keepFileName = false) {
  8. if (string.IsNullOrEmpty(fullName) || fullName.Length <= 200) return fullName;
  9. fullName = fullName.Replace('/', '\\');
  10. // 保留文件名
  11. string pathToKeep = "";
  12. string pathToShorten = fullName;
  13. if (fullName.EndsWithF(".jar", true)) keepFileName = true; // jar 文件的文件名需要保留原样,否则会导致 Forge 1.20.1 无法通过文件名识别模块名
  14. if (keepFileName && File.Exists(fullName)) {
  15. pathToKeep = Path.GetFileName(fullName);
  16. pathToShorten = Path.GetDirectoryName(fullName);
  17. }
  18. // 逐级向上寻找已存在的文件夹,将不存在的部分挪到 suffix,不再缩短
  19. while (!Directory.Exists(pathToShorten) && !File.Exists(pathToShorten)) { // 如果路径不存在
  20. string parentPath = Path.GetDirectoryName(pathToShorten);
  21. if (string.IsNullOrEmpty(parentPath) || parentPath == pathToShorten) return fullName; // 已经到达根目录,全都不存在,直接返回
  22. pathToKeep = Path.Combine(Path.GetFileName(pathToShorten), pathToKeep);
  23. pathToShorten = parentPath;
  24. }
  25. if (pathToShorten.Length <= 10) return fullName;
  26. // 缩短路径
  27. var buffer = new StringBuilder(260);
  28. if (GetShortPathNameW(pathToShorten, buffer, buffer.Capacity) == 0) return fullName;
  29. return Path.Combine(buffer.ToString(), pathToKeep);
  30. }
  31. [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
  32. private static extern int GetShortPathNameW(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer);
  33. }