我正在开发的应用需要处理文件名/路径名非常长的文件。这是一个 .Net 4.6 应用程序,因此我已经实现了 4.6.2 之前的解决方法以允许\\?\语法,如 here 所述和 here .
这是我用来启用该功能的代码(我无法修改 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] 命名空间中具有相同的注册表设置。
这台机器上的错误信息是:
The given path format is not supported
我们可以在该机器上看到的一个区别是,当在 Windows 文件资源管理器中查看一个非常长的文件时,“位置”字段使用 r-click > 属性菜单中的\\?\语法。
我猜测有一些注册表项导致了文件资源管理器中的差异以及我的修复失败,但不是在上面提到的 FileSystem 命名空间之外的其他地方。
有没有人遇到过类似的问题,或者知道其他可能相关的注册表区域?
最佳答案
你可以设置那些 AppContext
如果您不想在每个 App.config 文件中单独设置它们,则通过注册表在机器范围内切换:
这些设置将影响所有未在其 App.config 文件中指定不同值的 .NET 应用程序。也就是说,注册表设置仅更改默认值,仍然可以通过指定 <AppContextSwitchOverrides value="..." />
来使用特定于应用程序的值来覆盖它。
EnableLongPath.reg :
Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\AppContext] "Switch.System.IO.BlockLongPaths"="false" "Switch.System.IO.UseLegacyPathHandling"="false"
C:\>regedit.exe EnableLongPath.reg
关于c# - 长路径\\?\解决方法不适用于某些安装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53193280/