gpt4 book ai didi

c# - 从 PathTooLongException 中检索路径信息

转载 作者:可可西里 更新时间:2023-11-01 14:45:40 26 4
gpt4 key购买 nike

我在 .Net 4.0 中使用 DirectoryInfo 和 FileInfo 来枚举目录树中的文件,我遇到了 PathTooLongException。简化版如下

public static class Test
{
public static void Search(DirectoryInfo base)
{
foreach(var file in base.GetFiles())
{
try
{
Console.WriteLine(file.FullName);
} catch(PathTooLongException ex)
{
// What path was this?
}
}
foreach(var dir in base.GetDirectories())
{
Search(dir);
}
}
}

当抛出错误时,我想知道是什么文件路径导致了问题。显然我不能要求 FullName 因为这是错误的。我可以从 file.Name 获取名称,但如果我无法获取路径的其余部分,因为 file.Directory 会给出一个 PathTooLongException 甚至虽然从中找到文件的 DirectoryInfo 工作正常! (我不能使用它,因为实际代码要复杂得多)。

查看堆栈跟踪,它似乎正在使用内部路径(我从调试中看到一个 protected file.FullPath),并试图从完整(超大)路径中删除目录。大多数问题似乎涉及 System.IO.Path.NormalizePath,我听说在 .Net 4.0 中经历了一些变化。我没有尝试过以前版本的框架。

我的问题:

  1. 如何从这个异常中获取完整路径;它似乎在没有任何有用信息的情况下通过了。
  2. 为什么框架需要限制路径中的字符以截断文件名?

在此先感谢您的帮助,
安迪

最佳答案

除了使用反射,或者使用库或 P/Invoke 来使用支持长路径和手动检查长度的 Windows API,我想不出任何其他方法。完整路径存储在名为 FullPath

protected string 字段中
foreach(var dir in new DirectoryInfo (@"D:\longpaths")
.GetFileSystemInfos("*.*", SearchOption.AllDirectories))
{
try
{
Console.WriteLine(dir.FullName);
}
catch (PathTooLongException)
{
FieldInfo fld = typeof(FileSystemInfo).GetField(
"FullPath",
BindingFlags.Instance |
BindingFlags.NonPublic);
Console.WriteLine(fld.GetValue(dir)); // outputs your long path
}
}

如果您尝试实际上对文件做一些事情而不仅仅是检查文件长度,我建议使用像这样的库 from the BCL team at Microsoft ,但是它不会创建 DirectoryInfosFileInfoFileSystemInfo,只会创建字符串。所以它看起来可能不是您代码的直接替代品。

关于你第二个问题的答案,我建议阅读this blog post在 .NET 中处理长路径。这是它的引述,解释了为什么他们没有快速在 .NET 中添加长路径支持。

Very few people complain about a 32K limit, so, problem solved? Not quite. There are several reasons we were reluctant to add long paths in the past, and why we’re still careful about it, related to security, inconsistent support in the Windows APIs of the \?\ syntax, and app compatibility.

这是一个由 3 部分组成的系列,解释了 API 为何如此以及存在限制的几个原因。

关于c# - 从 PathTooLongException 中检索路径信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9589146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com