'Why do I still have a DirectoryNotFoundException because of Path Too Long under .NET 4.7.2?

.NET 4.6.2 announced it removed the maximum path length restriction of 260 characters in System.IO APIs.

The absence of targeting the .NET Framework 4.6.2 or setting the AppContext switch results in the existing behavior of being blocked from using paths longer than MAXPATH. The behavior is opt-in to maintain backwards compatibility for existing applications.

(emphasis mine).

I supposed that under .NET 4.7.2, I would no longer need to write failsafes to prevent this MAXPATH issue.

However, this code will throw a System.IO.DirectoryNotFoundException as soon as sourceDirectoryName is larger than 260 characters.

var sourceDirectoryName = @"C:\Users\MYUSER___\Documents\Sandbox\temp\OneDrive_1_11-04-2022\MySuperProject_With_Long_Name_Prefix\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bundle";
var destinationArchiveFileName = @"C:\Users\MYUSER___\Documents\Sandbox\temp\OneDrive_1_11-04-2022\MySuperProject_With_Long_Name_Prefix\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bundle.out";
ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName);

Why do I still have issues with large paths even though I am under .NET 4.7.2 ?



Solution 1:[1]

Maybe I'm reading that sentence incorrectly,

The absence of targeting the .NET Framework 4.6.2 or setting the AppContext switch results in the existing behavior of being blocked from using paths longer than MAXPATH. The behavior is opt-in to maintain backwards compatibility for existing applications.

but it seemed to me that the simple fact of targeting .NET 4.7.2 would result in the behavior of allowing paths longer than MAXPATH.

Nevertherless, I had to manually enable it in the app.manifest

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

The code doesn't trigger any exception anymore.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arthur Attout