writefile (kernel32)
Last changed: 68.12.43.92

.
Summary

C# Signature:

[DllImport("kernel32.dll")]
static extern bool WriteFile(IntPtr hFile, byte [] lpBuffer,
   uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten,
   [In] ref System.Threading.NativeOverlapped lpOverlapped);

or

[DllImport("kernel32.dll", SetLastError=true)]
static extern unsafe int WriteFile(IntPtr handle, IntPtr buffer,
  int numBytesToWrite, IntPtr numBytesWritten, NativeOverlapped* lpOverlapped);

VB Signature:

<DllImport("kernel32.dll", SetlastError:=True)> _
  Private Shared Function WriteFile(ByVal hFile As IntPtr, ByVal Buffer As IntPtr,
    ByVal nNumberOfBytesToWrite As Integer, ByRef lpNumberOfBytesWritten As Integer,
    ByRef lpOverlapped As OVERLAPPED) As Integer
  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 WriteFileScatter).

For more information on unbuffered IO in .NET see:

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

Tips & Tricks:

Please add some!

Sample Code:

  Public Sub Write(ByVal Packet As stArcnetPacket, ByVal DataLength As Int16)
    Dim dwErrorCode As FarcConstants
    Dim dwBytesWritten As Int32
    Dim ip As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(Packet))
    Marshal.StructureToPtr(Packet, ip, True)
    If WriteFile(hDriver, ip, DataLength + 6, dwBytesWritten, Nothing) Then
      Marshal.FreeHGlobal(ip)
    Else
      dwErrorCode = Marshal.GetLastWin32Error
      Marshal.FreeHGlobal(ip)
      Throw New System.IO.IOException("Write fails. Errorcode: " & dwErrorCode.ToString, _
        New System.ComponentModel.Win32Exception(dwErrorCode))
    End If
  End Sub

Alternative Managed API:

System.IO.FileStream

See Also

ReadFile, WriteFileGather, ReadFileScatter

Documentation
WriteFile on MSDN