System.IO.PathTooLongException:“指定的路径或文件名太长,或者二者都太长。彻底限定文件名必须少于 260 个字符,而且目录名必须少于 248 个字符。”git
NET 4.5github
在C#API中读取文件或文件夹时,彻底限定文件名必须少于 260 个字符,而且目录名必须少于 248 个字符。(System.IO
源码中作的限制)网络
使用第三方开源库ZetaLongPaths ,NuGet中使用1.0.0.24的版本,更高版本须要 NET 4.5.2 框架。框架
System.IO.FileInfo
的类,它包装函数以处理文件路径。System.IO.DirectoryInfo
的类,它包装函数以处理文件夹路径。System.IO.Path
的静态函数,用于路径。代码示例及比较函数
ZetaLongPaths.ZlpPathHelper.Combine(Path, tpName); //System.IO.Path.Combine(Path, tpName); ZetaLongPaths.ZlpPathHelper.Combine(null, null, null, names.ToArray()); //System.IO.Path.Combine(names.ToArray()); ZetaLongPaths.ZlpIOHelper.GetFiles(dirpath, "*"); //System.IO.Directory.GetFiles(dirpath, "*.*"); ZetaLongPaths.ZlpPathHelper.GetFileNameWithoutExtension(mDir); //System.IO.Path.GetFileNameWithoutExtension(m_Dir); ZetaLongPaths.ZlpIOHelper.DeleteFile(filePath); //System.IO.File.Delete(filePath); var directory = new ZlpDirectoryInfo(dirPath); //var directory = new DirectoryInfo(dirPath); ZetaLongPaths.ZlpPathHelper.GetDirectoryPathNameFromFilePath(path); //System.IO.Path.GetDirectoryName(path); ZetaLongPaths.ZlpIOHelper.DirectoryExists(folderPath); //System.IO.Directory.Exists(folderPath); ZetaLongPaths.ZlpIOHelper.CreateDirectory(folderPath); //Directory.CreateDirectory(folderPath);
System.IO
的接口规范有不小的区别,使用时须要逐个确认并替换System.IO.File
)的相关操做的支持,例如使用File.Open(string path, FileMode mode)
或者new FileStream(string path, FileMode mode)
类型时,仍是会由于文件名长度问题,报长度或者其余异常。使用第三方开源库AlphaFS,它为.NET平台提供比标准System.IO
类更完整的Win32文件系统功能支持的功能。code
Alphaleonis.Win32.Filesystem
的类名以及接口很规范,可以无缝替换System.IO
库比较大(359KB)blog
使用“\\?\”做为文件名前缀并调用Windows API的Unicode版本接口
升级框架NET 4.6.2及其以上版本以解决上述bug事务