错误及异常处理-[PathTooLongException]指定的路径或文件名太长

错误信息

System.IO.PathTooLongException:“指定的路径或文件名太长,或者二者都太长。彻底限定文件名必须少于 260 个字符,而且目录名必须少于 248 个字符。”git

环境

NET 4.5github

缘由分析

在C#API中读取文件或文件夹时,彻底限定文件名必须少于 260 个字符,而且目录名必须少于 248 个字符。(System.IO源码中作的限制)网络

解决方案

方案1

使用第三方开源库ZetaLongPaths ,NuGet中使用1.0.0.24的版本,更高版本须要 NET 4.5.2 框架。框架

功能:

  • ZlpFileInfo- 相似于System.IO.FileInfo的类,它包装函数以处理文件路径。
  • ZlpDirectoryInfo- 相似于System.IO.DirectoryInfo的类,它包装函数以处理文件夹路径。
  • ZlpIOHelper-一组静态函数,以提供相似的功能,做为ZlpFileInfo与ZlpDirectoryInfo类,但在静态上下文。
  • ZlpPathHelper- 一组相似于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);

优势

  • 能知足大部分文件和文件夹的操做
  • 轻量(65KB)

缺点

  • System.IO的接口规范有不小的区别,使用时须要逐个确认并替换
  • 缺乏对文件流(System.IO.File)的相关操做的支持,例如使用File.Open(string path, FileMode mode)或者new FileStream(string path, FileMode mode)类型时,仍是会由于文件名长度问题,报长度或者其余异常。

方案2

使用第三方开源库AlphaFS,它为.NET平台提供比标准System.IO类更完整的Win32文件系统功能支持的功能。code

功能

  • 支持扩展长度路径(最长32000个字符)
  • 建立链接点/硬连接
  • 访问隐藏的卷
  • 卷的枚举
  • 事务性文件操做
  • 支持NTFS备用数据流(文件/文件夹)
  • 访问网络资源(SMB / DFS)
  • 建立和访问名称中包含前导/尾随空格的文件夹/文件
  • 支持自定义筛选和错误报告/恢复的文件夹/文件枚举器(访问被拒绝的例外)

优势

  • Alphaleonis.Win32.Filesystem的类名以及接口很规范,可以无缝替换System.IO
  • 功能全面强大

缺点

库比较大(359KB)blog

方案3

使用“\\?\”做为文件名前缀并调用Windows API的Unicode版本接口

方案4

升级框架NET 4.6.2及其以上版本以解决上述bug事务

参考

相关文章
相关标签/搜索