Accessing files beyond MAX_PATH in C#/.NET

穿精又带淫゛_ 提交于 2019-11-29 04:06:13

The BCL team did a 3 part series on exactly why these choices were made and what the work arounds are. If you haven't read that yet I suggest you do as it's a great source of information on the subject

I ran into one third-party solution that may help: AlphaFS.

It should be fairly easy to work around this limitation with a bit of platform invoke, assuming your software has the necessary permissions:

[DllImport("kernel32.dll", SetLastError = true)]
static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
  uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
  uint dwFlagsAndAttributes, IntPtr hTemplateFile);

// Must close/dispose handle separately from FileStream since it's not owned by
// that object when passed to constructor.
using (SafeFileHandle h = CreateFile(longUncPath, GENERIC_WRITE, 0, IntPtr.Zero, 
       OPEN_EXISTING, 0, IntPtr.Zero))
{
    using (var fs = new FileStream(h, FileAccess.Read))
    {
        // operations with FileStream object
    }
}

You could try shortening the path by mapping a parent directory using subst.exe (or whatever APIs it uses internally):

http://www.makeuseof.com/tag/how-to-map-a-local-windows-folder-to-a-drive-letter/

Ideally you'd map away as much as possible of the path.

I have had success deleting directory structures using below small script. pushd uses UNC format which gives you 32K instead of 260 limitation

set "folder=\\SERVER\SHARE\DIVISION\DEPARTMENT\NAME OF TEAM - COULD BE FAIRLY LONG\" 
pushd "%folder%"
for /d %%i in ("*") do rmdir "%%i" /s /q
popd
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!