我正在开发的应用程序需要处理具有很长文件/路径名的文件。这是一个 .Net 4.6 应用程序,因此我实现了 4.6.2 之前的解决方法,以允许使用 \\?\ 语法,如概述的here https://stackoverflow.com/questions/41337607/prepending-doesnt-work-for-handling-long-paths and here https://stackoverflow.com/questions/5188527/how-to-deal-with-files-with-a-name-longer-than-259-characters.
这是我用来启用该功能的代码(我无法修改 app.config,因此必须在代码中设置):
var type = Type.GetType("System.AppContext");
if (type != null)
{
AppContext.SetSwitch("Switch.System.IO.UseLegacyPathHandling", false);
AppContext.SetSwitch("Switch.System.IO.BlockLongPaths", false);
var switchType = Type.GetType("System.AppContextSwitches");
if (switchType != null)
{
// We also have to reach into System.AppContextSwitches and manually update the cached private versions of these properties (don't ask me why):
var legacyField = switchType.GetField("_useLegacyPathHandling", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
legacyField?.SetValue(null, (Int32)(-1)); // <- caching uses 0 to indicate no value, -1 for false, 1 for true.
var blockingField = switchType.GetField("_blockLongPaths", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
blockingField?.SetValue(null, (Int32)(-1)); // <- caching uses 0 to indicate no value, -1 for false, 1 for true.
}
}
这在我们测试过的所有机器上都有效(耶!),除了一个(嘘!)。与其他计算机一样,有问题的计算机是 Windows 10 Pro 安装,并且在 [Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem] 命名空间中具有相同的注册表设置。
该特定机器上的错误消息是:
不支持给定的路径格式
我们在该计算机上看到的一个区别是,当在 Windows 文件资源管理器中查看非常长的文件时,“位置”字段使用 r 单击 > 属性菜单中的 \\?\ 语法。
我猜测有一些注册表项导致了文件资源管理器中的差异以及我的修复失败,但不是上面提到的文件系统命名空间。
有没有人遇到过类似的问题,或者知道其他可能相关的注册表区域?