c# - 为什么 .NET 无法检测具有长文件路径的目录?

标签 c# .net long-filenames pathtoolongexception

如果目录中包含的文件的完整路径超过 260 个字符,我将无法枚举这些文件。下面的代码显示了这个问题:

void TestLongPath(DirectoryInfo testDirectory)
{
    if (testDirectory.Exists)
    {
        try
        {
            testDirectory.GetFiles("SomeFileNamePattern*");
        }
        catch (System.IO.DirectoryNotFoundException)
        {
            Console.WriteLine("Long path test failed for " + testDirectory.FullName);
        }
    }
}

我的 app.manifest 文件包含:

<application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
        <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
    </windowsSettings>
</application>

但所做的只是将错误从 PathTooLongException 更改为 DirectoryNotFoundException。

这是我的应用程序配置:

<?xml version="1.0" encoding="utf-8"?><configuration>
<startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
</startup>
<runtime>
    <AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false" />
</runtime></configuration>

我使用的是 Windows 10 专业版,使用 Visual Studio 2019 16.1.1。我的目标是 .NET 4.7.2。

如何枚举这些超长目录中的文件?它们位于我无法控制的共享网络驱动器上,因此重命名目录不适合我。

最佳答案

我已经使用这里的信息解决了这个问题:What is the maximum amount of characters or length for a Directory?

对于 .NET 4.6.2 或更高版本: App.Config 中的“Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false”无效。

您不需要在路径前添加\\?\

您确实需要将注册表项 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled 设置为 1。

你确实需要

<application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
        <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
    </windowsSettings>
</application>

在您的 app.manifest 文件中。

此代码似乎总是返回 260,即使启用了长路径:

FieldInfo maxPathField = typeof(Path).GetField("MaxPath",
                     BindingFlags.Static |
                     BindingFlags.GetField |
                     BindingFlags.NonPublic);

int maxPathLength = (int)maxPathField.GetValue(null);
Console.WriteLine("Max path length is " + maxPathLength);

关于c# - 为什么 .NET 无法检测具有长文件路径的目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56547745/

相关文章:

c# - 模型状态错误的全局处理程序

.Net 自定义跟踪文件名

c# - Windows 10 最大路径长度限制

encryption - encfs 中的文件名长度限制是否有解决方法?

c# - 一个 Select 语句返回 uint 而另一个在同一列上返回 Int64?

c# - 试试{}捕获优化?

c# - Roslyn 代码分析器——什么时候应该使用 "this."?

ruby - 如何从 ARGV 获取长文件名

c# - 什么是 MVP-Passive View 和 MVP-Supervising controller

c# - 如何在一个 VS 解决方案中运行 NUnit 测试之前启动控制台应用程序?