简单的解决方案是将使用启用unc的路径,该路径将允许最多大约32767个字符的文件路径
string longPathEnabledFileName = Path.ToLongPath("C:\SomeVeryLongPath\....");
FileStream fs = new FileStream(longPathEnabledFileName);
这将简单地在路径前面加上 \\?\ ,告诉框架绕过 260 个字符的 MAX_PATH 限制。很遗憾, \\?\ 的前缀是不支持在撰写本文时在 .Net 中(截至版本 4.0)
- http://msdn.microsoft.com/en-us/library/aa365247.aspx http://msdn.microsoft.com/en-us/library/aa365247.aspx
这给我们留下了一个 WinApi 解决方案并引用 Kernel32.dll 来使用 SafeFileHandle。 BCL 团队的 Kim Hamilton 在博客中发布了一系列针对 MAX_PATH 限制的解决方法(第 2 部分展示了如何使用 winapi 函数),其中包含一个代码片段以供参考:
// 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);
}
}
http://blogs.msdn.com/b/bclteam/archive/2007/02/13/long-paths-in-net-part-1-of-3-kim-hamilton.aspx http://blogs.msdn.com/b/bclteam/archive/2007/02/13/long-paths-in-net-part-1-of-3-kim-hamilton.aspx
http://blogs.msdn.com/b/bclteam/archive/2007/03/26/long-paths-in-net-part-2-of-3-long-path-workarounds-kim-hamilton.aspx http://blogs.msdn.com/b/bclteam/archive/2007/03/26/long-paths-in-net-part-2-of-3-long-path-workarounds-kim-hamilton.aspx
http://blogs.msdn.com/b/bclteam/archive/2008/07/07/long-paths-in-net-part-3-of-3-redux-kim-hamilton.aspx http://blogs.msdn.com/b/bclteam/archive/2008/07/07/long-paths-in-net-part-3-of-3-redux-kim-hamilton.aspx
还有一个库封装了谷歌代码中的所有这些工作,称为 zeta 长路径
- http://code.google.com/p/zetalongpaths/ http://code.google.com/p/zetalongpaths/