DirectoryNotFoundException when using long paths in .NET 4.7

The Anniversary Update (RS1) has a bug that allow long paths to work without the manifest. For any updated Windows you must add the Application Manifest File item to your project. Otherwise it will not work.

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

This might not answer your question but give you a tip for a workaround. I tested your snippet with mono 4.5 under Ubuntu Linux and works like a charm, but in Windows the story might be a little bit different. Here, the one to blame seems to be the .NET Framework itself, regarding this article and this other article, does not support long paths.

Therefore, the solution as @Anastasiosyal suggest in this StackOverflow answer is to rely on the Windows Api itself. There are two ways: direct bypassing or Api call.

Directory.CreateDirectory(@"\\?\" + veryLongPath);

Api call (code is not mine, got it from @Anastasiosyal answer):

// This code snippet is provided under the Microsoft Permissive License.
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SafeFileHandle CreateFile(
    string lpFileName,
    EFileAccess dwDesiredAccess,
    EFileShare dwShareMode,
    IntPtr lpSecurityAttributes,
    ECreationDisposition dwCreationDisposition,
    EFileAttributes dwFlagsAndAttributes,
    IntPtr hTemplateFile);

public static void TestCreateAndWrite(string fileName) {

    string formattedName = @"\\?\" + fileName;
    // Create a file with generic write access
    SafeFileHandle fileHandle = CreateFile(formattedName,
        EFileAccess.GenericWrite, EFileShare.None, IntPtr.Zero,
        ECreationDisposition.CreateAlways, 0, IntPtr.Zero);

    // Check for errors
    int lastWin32Error = Marshal.GetLastWin32Error();
    if (fileHandle.IsInvalid) {
        throw new System.ComponentModel.Win32Exception(lastWin32Error);
    }

    // Pass the file handle to FileStream. FileStream will close the
    // handle
    using (FileStream fs = new FileStream(fileHandle,
                                    FileAccess.Write)) {
        fs.WriteByte(80);
        fs.WriteByte(81);
        fs.WriteByte(83);
        fs.WriteByte(84);
    }
}

In addition, I advise you to use Path.Combine instead of path + "\\" + subpath.