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

5

如果文件的完整路径超过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。

这是我的App.config:

<?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 Pro,Visual Studio 2019 16.1.1。我的目标是.NET 4.7.2。

如何枚举这些过长目录中的文件?它们存储在一个共享网络驱动器上,我无法控制,因此无法将目录重命名。


2
可能是重复问题。目录的最大字符数或长度是多少? - iamdlm
1个回答

1

我已经通过这里的信息解决了问题:目录的最大字符数或长度是多少?

对于.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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接