WriteFile有时会返回错误代码6

本文关键字:错误代码 返回 WriteFile | 更新日期: 2023-09-27 18:19:37

以下是代码片段:

创建文件代码:

m_RunFileHandle = CreateFile(strRunFullPath,
                             EFileAccess.GenericWrite,
                             EFileShare.None,
                             IntPtr.Zero, 
                             ECreationDisposition.CreateAlways,
                             EFileAttributes.Write_Through | EFileAttributes.NoBuffering,
                             IntPtr.Zero);

WriteFile代码:

WriteFile(m_RunFileHandle, NewFramePixelData, nDataSize, out nBytesWritten, IntPtr.Zero);

查询:WritrFile方法很少返回错误代码6。

WriteFile有时会返回错误代码6

如果在file_FLAG_OVERLAPPED模式下使用文件,则需要指向OVERLAPPED的结构的指针,否则请确保在不关闭句柄的情况下不会多次调用CreateFile。

在调用"WriteFile"之前,请检查是否多次调用CreateFile(不关闭以前创建的句柄)。在这种情况下,系统可能返回错误6。

溶剂为:

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool WriteFile(
    IntPtr hFile,
    byte[] lpBuffer,
    UInt32 nNumberOfBytesToWrite,
    ref UInt32 lpNumberOfBytesWritten,
    ref DriverEntity.OVERLAPPED lpOverlapped);

修改为:

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool WriteFile(
    IntPtr hFile,
    byte[] lpBuffer,
    UInt32 nNumberOfBytesToWrite,
    ref UInt32 lpNumberOfBytesWritten,
    IntPtr lpOverlapped);

用途:

DriverDAL.WriteFile(
    hDevice,
    writeBuffer,
    (uint)writeBuffer.Length,
    ref RealityWriteCount,
    IntPtr.Zero);