DirectoryNotFoundException when using long paths in .NET 4.7

Viewed 5216

I have set Enable Win32 Long Paths in the Local Group Policy Editor to Enabled and restarted the computer.

And here's the code:

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
for (int i = 0; i < 10; i++)
    path += "\\" + new string('z', 200);
Directory.CreateDirectory(path);

I'm getting the error:

System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Users...\Desktop\zzzzzzzzzz...

(Which is actually a strange error message.)

app.config already has:

<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7" />

More info (probably not important)

I tried adding as mentioned in this post and elsewhere (though as pointed out in the comments it's not needed when using .net 4.7) in app.config under configuration:

<runtime>
  <AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false" />
</runtime>

Still same error.

If I only use one zzzzzz... it creates it on the desktop with no error.

I'm using VS2017, Windows 10. I tried Winforms and WPF.

3 Answers

I have an experience:

1) in desktop application (.NET 4.7) you not need nothing more, then use path name with prefix @"\?\ (don't need manifest, set UseLegacyPathHandling in app.confing) and all works

2) in web application you have to set this:

  bool legacyPaths;
  if (AppContext.TryGetSwitch("Switch.System.IO.UseLegacyPathHandling", out legacyPaths) && legacyPaths)
  {
    var switchType = Type.GetType("System.AppContextSwitches"); 
    if (switchType != null)
    {
      AppContext.SetSwitch("Switch.System.IO.UseLegacyPathHandling", false);   
      var legacyField = switchType.GetField("_useLegacyPathHandling", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
      legacyField?.SetValue(null, (Int32)0); 
      AppContext.TryGetSwitch("Switch.System.IO.UseLegacyPathHandling", out legacyPaths);
      Assert.IsFalse(legacyPaths, "Long pathnames are not supported!");
    }
  }

I hope the help you!

Related