C#: Long Path with UseLegacyPathHandling and BlockLongPaths not working

3.6k Views Asked by At

I'm using C# with .NET v4.7.2 and Windows 10 and I have some files with long path (>260 characters in the paths) to copy.

I know there is a solution to prefix the path by \\?\

This prefix is working, but I do not want to prefix everytime for any file operation. since .Net v4.6.2 there is be a better solution by AppContext-Switches UseLegacyPathHandling and BlockLongPaths.

However this is not working.

My app.config looks like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
  </startup>
  <windowsSettings>
    <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
  </windowsSettings>
  <runtime>
    <AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false" />
  </runtime> 
</configuration>

My C# looks like this:

public static void Main(string[] args)
{
   string src = @"c:\Temp\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.txt";
   string dst = @"c:\Temp\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-123.txt";
   File.Copy(src, dst);
}

My Problem

  • With .NET v4.5, File.Copy() throws a System.IO.PathTooLongException

  • With .NET v4.7.2 File.Copy() throws a System.IO.DirectoryNotFoundException

I checked by AppContext.TryGetSwitch() if the switches are set, and they are. So I don't know how to get I to work.

What am I doing wrong?

1

There are 1 best solutions below

2
On

Your filename is 317 characters long, which exceeds the 255 characters allowed in an NTFS path segment (#1, #2).

(In retrospect, it was probably a mistake for Jeremy to use an example that couldn't possibly work on any filesystem in #2!)