CreateFile、FILE_FLAG_BACKUP_SEMANTICS、目录管理和句柄

CreateFile, FILE_FLAG_BACKUP_SEMANTICS, Directory Management and Handles

本文关键字:管理 句柄 BACKUP FILE FLAG CreateFile SEMANTICS      更新时间:2023-10-16

我正试图获取一个目录句柄,以便检索目录的标识符。文档(链接到上面)指定FILE_FLAG_BACKUP_SEMANTICS标志需要传递给CreateFile函数,以便检索句柄本身。

然而,在查阅pinvoke的kernel32.dll签名时,大多数C#候选看起来如下:

    [DllImport("kernell32.dll", SetLastError = true)]
    public static extern SafeFileHandle CreateFile(
        string lpFileName,
        [MarshalAs(UnmanagedType.U4)] FileAccess dwDesiredAccess,
        [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode,
        IntPtr securityAttributes,
        [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition,
        [MarshalAs(UnmanagedType.U4)] FileAttributes dwFlagsAndAttributes,
        IntPtr hTemplateFile
    );

上述一对一参数映射到C++CreateFile意味着dwFlagsAndAttributes参数是FILE_FLAG_BACKUP_SEMANTICS的占位符;但是,FileAttribute枚举似乎与该标志不匹配。

现在(它坏了)我的电话看起来像:

           var createdFolder =
                FileSystemInteractor.CreateFile(
                    fullPathWithFolderName,
                    FileAccess.Read,
                    FileShare.Read,
                    IntPtr.Zero,
                    FileMode.Open,
                    Kernel32.FILE_FLAG_BACKUP_SEMANTICS,
                    IntPtr.Zero
                );

CCD_ 7显然包含了正确的标志。收到的编译器错误是:

无法从"uint"转换为"System.IO.FileAttributes"

这个错误是有道理的;我只是不确定我能做什么按摩签名,因为我是extern函数的新手。

是否有对应于所需标志的FileAttributes?我需要更改extern签名吗?

在代码中包含此枚举定义:

[Flags]
private enum File_Attributes : uint
{
    Readonly = 0x00000001,
    Hidden = 0x00000002,
    System = 0x00000004,
    Directory = 0x00000010,
    Archive = 0x00000020,
    Device = 0x00000040,
    Normal = 0x00000080,
    Temporary = 0x00000100,
    SparseFile = 0x00000200,
    ReparsePoint = 0x00000400,
    Compressed = 0x00000800,
    Offline = 0x00001000,
    NotContentIndexed = 0x00002000,
    Encrypted = 0x00004000,
    Write_Through = 0x80000000,
    Overlapped = 0x40000000,
    NoBuffering = 0x20000000,
    RandomAccess = 0x10000000,
    SequentialScan = 0x08000000,
    DeleteOnClose = 0x04000000,
    BackupSemantics = 0x02000000,
    PosixSemantics = 0x01000000,
    OpenReparsePoint = 0x00200000,
    OpenNoRecall = 0x00100000,
    FirstPipeInstance = 0x00080000
}

System.IO中定义的文件属性不包括许多属性。