以编程方式检查Windows 10的区分大小写的目录属性

时间:2018-09-06 14:20:31

标签: c# windows winapi

自2018年4月以来,Windows 10能够获取或设置是否使用fsutil.exe将目录标记为区分大小写。

有没有一种方法可以通过编程方式查询目录的区分大小写,而无需运行fsutil.exe或通过使用不同大小写的格式伪造文件来查看它们是否冲突?

我还没有真正找到通过研究测试这一点的方法。我读过这是一个实际的NTFS属性,但在获取文件属性时却没有显示。我还注意到,如果存在两个不同的大小写,FindFirstFile将返回正确文件的大小写。除此之外,我不知道要去哪里,因为实际上没有很多信息。这些东西仍然很新。

正如其他人所提到的,由于可比性问题,区分大小写在Windows中不是一个好主意。我意识到了这一点,我的目标是扫描文件系统中现有的区分大小写的目录并使用它。

进度:

我发现Windows的FindFirstFile和friends函数即使不使用FIND_FIRST_EX_CASE_SENSITIVE也尊重目录的区分大小写。它不会返回带有无效大小写的文件。现在,我试图找出是否有一个很好的方法可以利用这一点。

1 个答案:

答案 0 :(得分:3)

在@eryksun的评论帮助下,这是我的P / Invoke解决方案。

编辑2:添加了SetDirectoryCaseSensitive()

编辑3:添加了IsDirectoryCaseSensitivitySupported()

我已经在使用NtQueryInformationFile FileCaseSensitiveInformation来读取FILE_INFORMATION_CLASS结构的同时实现了本地方法FILE_CASE_SENSITIVE_INFORMATION

public static partial class NativeMethods {
    public static readonly IntPtr INVALID_HANDLE = new IntPtr(-1);

    public const FileAttributes FILE_FLAG_BACKUP_SEMANTICS = (FileAttributes) 0x02000000;

    public enum NTSTATUS : uint {
        SUCCESS = 0x00000000,
        NOT_IMPLEMENTED = 0xC0000002,
        INVALID_INFO_CLASS = 0xC0000003,
        INVALID_PARAMETER = 0xC000000D,
        NOT_SUPPORTED = 0xC00000BB,
        DIRECTORY_NOT_EMPTY = 0xC0000101,
    }

    public enum FILE_INFORMATION_CLASS {
        None = 0,
        // Note: If you use the actual enum in here, remember to
        // start the first field at 1. There is nothing at zero.
        FileCaseSensitiveInformation = 71,
    }

    // It's called Flags in FileCaseSensitiveInformation so treat it as flags
    [Flags]
    public enum CASE_SENSITIVITY_FLAGS : uint {
        CaseInsensitiveDirectory = 0x00000000,
        CaseSensitiveDirectory = 0x00000001,
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct IO_STATUS_BLOCK {
        [MarshalAs(UnmanagedType.U4)]
        public NTSTATUS Status;
        public ulong Information;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct FILE_CASE_SENSITIVE_INFORMATION {
        [MarshalAs(UnmanagedType.U4)]
        public CASE_SENSITIVITY_FLAGS Flags;
    }

    // An override, specifically made for FileCaseSensitiveInformation, no IntPtr necessary.
    [DllImport("ntdll.dll")]
    [return: MarshalAs(UnmanagedType.U4)]
    public static extern NTSTATUS NtQueryInformationFile(
        IntPtr FileHandle,
        ref IO_STATUS_BLOCK IoStatusBlock,
        ref FILE_CASE_SENSITIVE_INFORMATION FileInformation,
        int Length,
        FILE_INFORMATION_CLASS FileInformationClass);

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern IntPtr CreateFile(
            [MarshalAs(UnmanagedType.LPTStr)] string filename,
            [MarshalAs(UnmanagedType.U4)] FileAccess access,
            [MarshalAs(UnmanagedType.U4)] FileShare share,
            IntPtr securityAttributes, // optional SECURITY_ATTRIBUTES struct or IntPtr.Zero
            [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
            [MarshalAs(UnmanagedType.U4)] FileAttributes flagsAndAttributes,
            IntPtr templateFile);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool CloseHandle(
        IntPtr hObject);

    public static bool IsDirectoryCaseSensitive(string directory, bool throwOnError = true) {
        // Read access is NOT required
        IntPtr hFile = CreateFile(directory, 0, FileShare.ReadWrite,
                                    IntPtr.Zero, FileMode.Open,
                                    FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);
        if (hFile == INVALID_HANDLE)
            throw new Win32Exception();
        try {
            IO_STATUS_BLOCK iosb = new IO_STATUS_BLOCK();
            FILE_CASE_SENSITIVE_INFORMATION caseSensitive = new FILE_CASE_SENSITIVE_INFORMATION();
            NTSTATUS status = NtQueryInformationFile(hFile, ref iosb, ref caseSensitive,
                                                        Marshal.SizeOf<FILE_CASE_SENSITIVE_INFORMATION>(),
                                                        FILE_INFORMATION_CLASS.FileCaseSensitiveInformation);
            switch (status) {
            case NTSTATUS.SUCCESS:
                return caseSensitive.Flags.HasFlag(CASE_SENSITIVITY_FLAGS.CaseSensitiveDirectory);

            case NTSTATUS.NOT_IMPLEMENTED:
            case NTSTATUS.NOT_SUPPORTED:
            case NTSTATUS.INVALID_INFO_CLASS:
            case NTSTATUS.INVALID_PARAMETER:
                // Not supported, must be older version of windows.
                // Directory case sensitivity is impossible.
                return false;
            default:
                throw new Exception($"Unknown NTSTATUS: {(uint)status:X8}!");
            }
        }
        finally {
            CloseHandle(hFile);
        }
    }
}

这里是通过实现NTSetInformationFile来设置目录区分大小写的实现。 (其中的参数列表与NTQueryInformationFile相同。同样,由于@eryksun的见识,该问题得以解决。

FILE_WRITE_ATTRIBUTES是未在C#中实现的FileAccess标志,因此需要从值0x100进行定义和/或强制转换。

partial class NativeMethods {
    public const FileAccess FILE_WRITE_ATTRIBUTES = (FileAccess) 0x00000100;

    // An override, specifically made for FileCaseSensitiveInformation, no IntPtr necessary.
    [DllImport("ntdll.dll")]
    [return: MarshalAs(UnmanagedType.U4)]
    public static extern NTSTATUS NtSetInformationFile(
        IntPtr FileHandle,
        ref IO_STATUS_BLOCK IoStatusBlock,
        ref FILE_CASE_SENSITIVE_INFORMATION FileInformation,
        int Length,
        FILE_INFORMATION_CLASS FileInformationClass);

    // Require's elevated priviledges
    public static void SetDirectoryCaseSensitive(string directory, bool enable) {
        // FILE_WRITE_ATTRIBUTES access is the only requirement
        IntPtr hFile = CreateFile(directory, FILE_WRITE_ATTRIBUTES, FileShare.ReadWrite,
                                    IntPtr.Zero, FileMode.Open,
                                    FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);
        if (hFile == INVALID_HANDLE)
            throw new Win32Exception();
        try {
            IO_STATUS_BLOCK iosb = new IO_STATUS_BLOCK();
            FILE_CASE_SENSITIVE_INFORMATION caseSensitive = new FILE_CASE_SENSITIVE_INFORMATION();
            if (enable)
                caseSensitive.Flags |= CASE_SENSITIVITY_FLAGS.CaseSensitiveDirectory;
            NTSTATUS status = NtSetInformationFile(hFile, ref iosb, ref caseSensitive,
                                                    Marshal.SizeOf<FILE_CASE_SENSITIVE_INFORMATION>(),
                                                    FILE_INFORMATION_CLASS.FileCaseSensitiveInformation);
            switch (status) {
            case NTSTATUS.SUCCESS:
                return;
            case NTSTATUS.DIRECTORY_NOT_EMPTY:
                throw new IOException($"Directory \"{directory}\" contains matching " +
                                      $"case-insensitive files!");

            case NTSTATUS.NOT_IMPLEMENTED:
            case NTSTATUS.NOT_SUPPORTED:
            case NTSTATUS.INVALID_INFO_CLASS:
            case NTSTATUS.INVALID_PARAMETER:
                // Not supported, must be older version of windows.
                // Directory case sensitivity is impossible.
                throw new NotSupportedException("This version of Windows does not support directory case sensitivity!");
            default:
                throw new Exception($"Unknown NTSTATUS: {(uint)status:X8}!");
            }
        }
        finally {
            CloseHandle(hFile);
        }
    }
}

最后,如果Windows版本支持区分大小写的目录,我添加了一种计算一次的方法。这样只会在Temp中创建一个名称为GUID的文件夹,并检查NTSTATUS的结果(因此它可以检查它知道可以访问的文件夹)。

partial class NativeMethods {
    // Use the same directory so it does not need to be recreated when restarting the program
    private static readonly string TempDirectory =
        Path.Combine(Path.GetTempPath(), "88DEB13C-E516-46C3-97CA-46A8D0DDD8B2");

    private static bool? isSupported;
    public static bool IsDirectoryCaseSensitivitySupported() {
        if (isSupported.HasValue)
            return isSupported.Value;

        // Make sure the directory exists
        if (!Directory.Exists(TempDirectory))
            Directory.CreateDirectory(TempDirectory);

        IntPtr hFile = CreateFile(TempDirectory, 0, FileShare.ReadWrite,
                                IntPtr.Zero, FileMode.Open,
                                FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);
        if (hFile == INVALID_HANDLE)
            throw new Exception("Failed to open file while checking case sensitivity support!");
        try {
            IO_STATUS_BLOCK iosb = new IO_STATUS_BLOCK();
            FILE_CASE_SENSITIVE_INFORMATION caseSensitive = new FILE_CASE_SENSITIVE_INFORMATION();
            // Strangely enough, this doesn't fail on files
            NTSTATUS result = NtQueryInformationFile(hFile, ref iosb, ref caseSensitive,
                                                        Marshal.SizeOf<FILE_CASE_SENSITIVE_INFORMATION>(),
                                                        FILE_INFORMATION_CLASS.FileCaseSensitiveInformation);
            switch (result) {
            case NTSTATUS.SUCCESS:
                return (isSupported = true).Value;
            case NTSTATUS.NOT_IMPLEMENTED:
            case NTSTATUS.INVALID_INFO_CLASS:
            case NTSTATUS.INVALID_PARAMETER:
            case NTSTATUS.NOT_SUPPORTED:
                // Not supported, must be older version of windows.
                // Directory case sensitivity is impossible.
                return (isSupported = false).Value;
            default:
                throw new Exception($"Unknown NTSTATUS {(uint)result:X8} while checking case sensitivity support!");
            }
        }
        finally {
            CloseHandle(hFile);
            try {
                // CHOOSE: If you delete the folder, future calls to this will not be any faster
                // Directory.Delete(TempDirectory);
            }
            catch { }
        }
    }
}