Unity 2019 无法删除长路径文件

介绍

在执行 Directory.Delete 删除目录时,目录内部存在过深的子目录而完整路径超过 260 个字符,删除就会出现异常。

 1  2  3  4  5  6  7  8  9 10 11 12 13 14 
DirectoryNotFoundException: Could not find a part of the path "C:/Project/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Output/GradleProject/launcher/build/intermediates/desugar_graph/release/dexBuilderRelease/out/currentProject/jar_8644da973e7b1e319711ad5b4fbc94027d2acce4dda8b1bd6d51994cb312313d_bucket_0/graph.bin" at System.IO.File.Delete (System.String path) [0x00073] in <eae584ce26bc40229c1b1aa476bfa589>:0 at System.IO.Directory.RecursiveDelete (System.String path) [0x0003f] in <eae584ce26bc40229c1b1aa476bfa589>:0 at System.IO.Directory.RecursiveDelete (System.String path) [0x00024] in <eae584ce26bc40229c1b1aa476bfa589>:0 at System.IO.Directory.RecursiveDelete (System.String path) [0x00024] in <eae584ce26bc40229c1b1aa476bfa589>:0 at System.IO.Directory.RecursiveDelete (System.String path) [0x00024] in <eae584ce26bc40229c1b1aa476bfa589>:0 at System.IO.Directory.RecursiveDelete (System.String path) [0x00024] in <eae584ce26bc40229c1b1aa476bfa589>:0 at System.IO.Directory.RecursiveDelete (System.String path) [0x00024] in <eae584ce26bc40229c1b1aa476bfa589>:0 at System.IO.Directory.RecursiveDelete (System.String path) [0x00024] in <eae584ce26bc40229c1b1aa476bfa589>:0 at System.IO.Directory.RecursiveDelete (System.String path) [0x00024] in <eae584ce26bc40229c1b1aa476bfa589>:0 at System.IO.Directory.RecursiveDelete (System.String path) [0x00024] in <eae584ce26bc40229c1b1aa476bfa589>:0 at System.IO.Directory.RecursiveDelete (System.String path) [0x00024] in <eae584ce26bc40229c1b1aa476bfa589>:0 at System.IO.Directory.Delete (System.String path, System.Boolean recursive) [0x00009] in <eae584ce26bc40229c1b1aa476bfa589>:0 at Build.Export () [0x0008d] in C:/Project/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Build.cs:291 

环境

  • Windows 10 21H2
  • Unity 2019.4.41f1

分析

虽然传入的路径没有那么长,但是在 Directory.Delete 内部会使用递归删除子目录与子文件,导致路径超过 260 个字符限制。

Windows 启用长路径支持无效,使用 /?/ 前缀无效

- 文件命名、路径和命名空间 - Win32 apps | Microsoft Learn

本质原因是因为路径过长,Unity 内置 mono 系统库版本过老,无法删除长路径。

- mono/mcs/class/referencesource/mscorlib/system/io/directory.cs at main · mono/mono · GitHub

方案

Unity 2019

推荐使用外部工具删除目录,例如 rmdir 命令。

Unity 升级

实测 Unity 2022.3.62f1 没有这个问题,相同环境下相同代码可以正常删除。

推荐旧项目尽可能升级到最新的 LTS 版本。

版权声明:
作者:zhangchen
链接:https://www.techfm.club/p/231824.html
来源:TechFM
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>