有人能帮帮我吗?
我尝试从托管的.net代码P/Invoke
获取WINAPI方法。
CreateFile()
方法始终返回false。如果我使给定的路径小于256,它就可以正常工作,但如果大于256则不行。我可能做错了。
根据这个link,我应该能够使用长度大于256的长路径文件。
以下是我尝试过的代码:
static void Main(string[] args)
{
string path = @"c:\tttttttttttaaaaaaaaaaaaaaatttttttttttttttaaaaaaaaaaaaaaatttttttttttttttttttttttttttttttaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaattttttttttttttttttaaaaaaaaaaaaaaaaatttttttttttaaaaaaaaaaatttttttaaaaaaaaaaaaaaaaattttttttttttttttttaaaaaaaaaaaaaaaaattttttttttttttaaaaaaaaaaaaaaaaatttttt";
LongPath.TestCreateAndWrite(path);
}
// This code snippet is provided under the Microsoft Permissive License.
[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;
//string formattedName = @"\\?\UNC" + 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);
}
}
此方法抛出错误代码3,这是根据系统错误代码(0-499)(Windows)未指定的文件路径。
任何帮助都会非常明显。
答案 0 :(得分:3)
虽然\\?\
表示法允许您使用总长度超过MAX_PATH
的路径,但您仍必须遵守GetVolumeInformation
报告的每个组件限制。对于NTFS,每个组件的限制为255,这意味着如果没有反斜杠,则不允许超过255个字符。