Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Long Path with UseLegacyPathHandling and BlockLongPaths not working

I'm using C# with .Net v4.7.2 and Win10 and I have some files with long path (>260) 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# Code 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.

Can anybody explain, what I'd doing wrong? Thanx for any feedback!

-- jaz

like image 988
jaz Avatar asked Nov 07 '22 22:11

jaz


1 Answers

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!)

like image 150
Ian Kemp Avatar answered Nov 22 '22 05:11

Ian Kemp