ReadFile (kernel32)
Last changed: 78.138.23.195

.
Summary

C# Signature:

[DllImport("kernel32.dll")]
static extern bool ReadFile(IntPtr hFile, byte[] lpBuffer,
   uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped);

or

[DllImport("kernel32.dll", SetLastError=true)]
static extern unsafe int ReadFile(IntPtr handle, IntPtr bytes, uint numBytesToRead,
  IntPtr numBytesRead, NativeOverlapped* overlapped);

or

[DllImport("kernel32.dll", SetLastError=true)]
static extern bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer, uint nNumberOfBytesToRead,
   out uint lpNumberOfBytesRead, [In] ref System.Threading.NativeOverlapped lpOverlapped);

VB Signature:

<DllImport("kernel32.dll", SetlastError:=True)> _
  Private Shared Function ReadFile(ByVal hFile As IntPtr, ByVal Buffer As IntPtr, _
    ByVal nNumberOfBytesToRead As Integer, ByRef lpNumberOfBytesRead As Integer, _
    ByRef lpOverlapped As OVERLAPPED) As Integer
  End Function

or

<DllImport("kernel32.dll")> Friend Shared Function ReadFile( _
    ByVal File As SafeFileHandle, _
    ByVal Buffer As System.Text.StringBuilder, _
    ByVal NumberOfBytesToRead As Integer, _
    ByRef NumberOfBytesRead As Integer, _
    ByRef Overlapped As System.Threading.NativeOverlapped) As SafeFileHandle
End Function

User-Defined Types:

None.

Notes:

The documentation states that if using unbuffered IO, the memory must be "storage aligned" (aligned to the sector size of the storage device). Either this is not enforced, or managed allocations (specifically byte arrays) are automatically storage aligned because there seems to be no problem using it. Note that storage aligned and page aligned are not the same, and managed allocations are not in general page aligned (required for ReadFileScatter).

For more information on unbuffered IO in .NET see:

http://arxiv.org/abs/cs.PF/0502012

Tips & Tricks:

NET 2.0 use SafeFileHandle instead of IntPtr

Sample Code:

  Public Function Read() As stArcnetPacket
    Dim dwErrorCode As FarcConstants
    Dim erg As stArcnetPacket
    Dim dwBytesReceived As Int32
    Dim ip As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(erg))
    If ReadFile(hDriver, ip, Marshal.SizeOf(erg), dwBytesReceived, Nothing) Then
      erg = Marshal.PtrToStructure(ip, erg.GetType)
      ReDim Preserve erg.Data(dwBytesReceived - 6)
      Marshal.FreeHGlobal(ip)
    Else
      dwErrorCode = Marshal.GetLastWin32Error
      Marshal.FreeHGlobal(ip)
      Throw New System.IO.IOException("Read fails. Errorcode: " & _
    dwErrorCode.ToString, New System.ComponentModel.Win32Exception(dwErrorCode))
    End If
    Return erg
  End Function

Alternative Managed API:

System.IO.FileStream

See Also

WriteFile, WriteFileGather, ReadFileScatter

Documentation
ReadFile on MSDN