C# 中使用CreateFile遇到的坑

在C# 调用系统函数CreateFile函数,注意把共享模式设置为:可读写的,否则可能会出现Win7系统运行正常,Win10系统运行有问题;

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern IntPtr CreateFile(string fileName, uint desiredAccess, uint shareMode, uint securityAttributes, uint creationDisposition, uint flagsAndAttributes, uint templateFile);

引用示例:
IntPtr device = CreateFile(deviceList[i],
                            DESIREDACCESS.GENERIC_READ | DESIREDACCESS.GENERIC_WRITE,
                            SHAREMODE.FILE_SHARE_READ | SHAREMODE.FILE_SHARE_WRITE,
                            0,
                            CREATIONDISPOSITION.OPEN_EXISTING,
                            FLAGSANDATTRIBUTES.FILE_FLAG_OVERLAPPED,
                            0);

结构体定义
static class DESIREDACCESS
{
    public const uint GENERIC_READ = 0x80000000;
    public const uint GENERIC_WRITE = 0x40000000;
    public const uint GENERIC_EXECUTE = 0x20000000;
    public const uint GENERIC_ALL = 0x10000000;
}
/// 
/// Sharing mode of the file or object
///
static class SHAREMODE
{
    public const uint FILE_SHARE_READ = 0x00000001;
    public const uint FILE_SHARE_WRITE = 0x00000002;
    public const uint FILE_SHARE_DELETE = 0x00000004;
}
/// 
/// Action to take on files that exist, and which action to take when files do not exist.
/// 
static class CREATIONDISPOSITION
{
    public const uint CREATE_NEW = 1;
    public const uint CREATE_ALWAYS = 2;
    public const uint OPEN_EXISTING = 3;
    public const uint OPEN_ALWAYS = 4;
    public const uint TRUNCATE_EXISTING = 5;
}
/// 
/// File attributes and flags for the file.
/// 
static class FLAGSANDATTRIBUTES
{
    public const uint FILE_FLAG_WRITE_THROUGH = 0x80000000;
    public const uint FILE_FLAG_OVERLAPPED = 0x40000000;
    public const uint FILE_FLAG_NO_BUFFERING = 0x20000000;
    public const uint FILE_FLAG_RANDOM_ACCESS = 0x10000000;
    public const uint FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000;
    public const uint FILE_FLAG_DELETE_ON_CLOSE = 0x04000000;
    public const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
    public const uint FILE_FLAG_POSIX_SEMANTICS = 0x01000000;
    public const uint FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000;
    public const uint FILE_FLAG_OPEN_NO_RECALL = 0x00100000;
    public const uint FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000;
}

IntPtr device = CreateFile(deviceList[i],

                            DESIREDACCESS.GENERIC_READ | DESIREDACCESS.GENERIC_WRITE,

                            SHAREMODE.FILE_SHARE_READ | SHAREMODE.FILE_SHARE_WRITE,

                            0,

                            CREATIONDISPOSITION.OPEN_EXISTING,

                            FLAGSANDATTRIBUTES.FILE_FLAG_OVERLAPPED,

                            0);

注意红色标识部分,设置为读写共享模式,即可解决该上述问题;

你可能感兴趣的:(#,C#,遇坑记)