Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Download Visual Studio Add-In

WriteFile (kernel32)
 
.
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

or

  "File" = The SafeFileHandle to the file to write to. The file must have at least write-level access.
  "Buffer" = The variable, array, or string holding the data to write to the file.
  "NumberOfBytesToWrite" = The number of bytes of data to write to the file.
  "NumberOfBytesWritten" = Receives the number of bytes of data actually written to the file.
  "Overlapped" = If the file is asynchronous (overlapped), this is an threading.NativeOverlappedStructure specifying where to begin writing at. If the file is synchronous (not overlapped), this must be 0.

<DllImport("kernel32.dll")> Friend Shared Function WriteFile( _
    ByVal File As SafeFileHandle, _
    ByVal Buffer As System.Text.StringBuilder, _
    ByVal NumberOfBytesToWrite As Integer, _
    ByRef NumberOfBytesWritten As Integer, _
    ByRef Overlapped As System.Threading.NativeOverlapped) As IntPtr
  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).

In fact the buffer must be aligned to the granularity of the SCSI/IDE adapter's DMA alignment (PDEVICE_OBJECT->AlignmentRequirement). The MSDN documentation is written for the lamers and probably it seemed safe to restrict them using the sector size (which is >= 512 byte, while most modern SCSI cards use <=4 byte requirement).

For more information on unbuffered IO in .NET see:

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

Tips & Tricks:

NET 2.0 use the SafeFileHandle version

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

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Find References
Show Printable Version
Revisions