Accessing files beyond MAX_PATH in C#/.NET

前端 未结 5 1425
粉色の甜心
粉色の甜心 2020-12-16 20:56

BACKGROUND

I need to write a tool using .NET version 2.0 at highest (using something off the shelf is not an option for this client for political, c

5条回答
  •  一生所求
    2020-12-16 21:24

    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
        }
    }
    

提交回复
热议问题