1

任何人都可以帮助我吗?

我尝试P/Invoke从托管的 .net 代码中使用 WINAPI 方法。 CreateFile()方法总是返回假。如果我使给定的路径小于 256,它就可以正常工作,但如果大于 256,则不会。我可能做错了什么。根据此链接,我应该能够使用长度大于 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) 指定的文件路径。

任何帮助都将是非常可观的。

4

1 回答 1

3

虽然该\\?\符号允许您使用总长度大于 的路径MAX_PATH,但您仍然必须遵守 报告的每个组件限制GetVolumeInformation。对于 NTFS,每个组件的限制是 255,这意味着在没有反斜杠的情况下不允许超过 255 个字符。

于 2012-12-02T17:26:18.577 回答