我处理长文件路径的 WINAPI 调用有什么问题?
我一直在试图找出在 Windows 中使用深层路径复制文件的最佳方法(文件,而不是文件夹,因此 robocopy 是不可能的)。 我能想到的最好的解决方案是编写我自己的解决方案。 我已经能够编写代码来处理具有 10,000 个字符深度路径的列表目录,但使用相同的方法似乎不适用于实际复制文件。 我厌倦了使用带有 \?\ 前缀的 System.IO 库作为路径,但这似乎不起作用。
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CopyFile(string lpExistingFileName, string lpNewFileName,
bool bFailIfExists);
public static bool CopyFile(string source, string dest)
{
source = fixPathForLong(source);
dest = fixPathForLong(dest);
return CopyFile(source, dest, false);
}
private static string fixPathForLong(String path)
{
if (!path.StartsWith(@"\\?\"))
path = @"\\?\" + path;
return path;
}
I've been trying to figure out the best way to copy files in Windows with deep paths (files, not folders so robocopy is out of the question). The best solution I've been able to come up with is writing my own solution. I've been able to write the code to handle listing directories with 10,000 character deeps paths but using the same approach doesn't seem to be working for actually copying files. I tired using the System.IO libraries with \?\ prefixed to paths and that didn't seem to work.
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CopyFile(string lpExistingFileName, string lpNewFileName,
bool bFailIfExists);
public static bool CopyFile(string source, string dest)
{
source = fixPathForLong(source);
dest = fixPathForLong(dest);
return CopyFile(source, dest, false);
}
private static string fixPathForLong(String path)
{
if (!path.StartsWith(@"\\?\"))
path = @"\\?\" + path;
return path;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该调用函数 CopyFileW 吗? 注意最后的W。 另外,我不知道你是否使用 UNC 路径。 如果是这样,您需要添加前缀“\\?\UNC\”。
这是一篇关于长路径处理的好文章
http://blogs.msdn.com/bclteam/archive/2007/02/13/long-paths-in-net-part-1-of-3-kim -hamilton.aspx
Should you call the function CopyFileW instead? Note the W at the end. Also, i don't know if you are using UNC paths. If so you need to prefix with "\\?\UNC\" instead.
This is a good article for long path handling
http://blogs.msdn.com/bclteam/archive/2007/02/13/long-paths-in-net-part-1-of-3-kim-hamilton.aspx
如果对 CopyFile 的调用(不是您的重载,P/Invoke 声明)返回 false,我将抛出 Win32Exception:
Win32Exception 类的默认构造函数将调用 GetLastError 并为您提供有关操作失败原因的更详细的错误信息。
If the call to CopyFile (not your overload, the P/Invoke declaration) returns false I would throw a Win32Exception:
The default constructor for the Win32Exception class will make a call to GetLastError and give you more detailed error information as to why the operation failed.