как пример, импорты и константы кернела:
#region Constants
// Constants pris de WINERROR.H
internal const UInt32 ERROR_FILE_NOT_FOUND = 2;
internal const UInt32 ERROR_ACCESS_DENIED = 5;
internal const UInt32 ERROR_IO_PENDING = 997;
// Constants pris de WINBASE.H
internal const Int32 INVALID_HANDLE_VALUE = -1;
internal const UInt32 FILE_FLAG_OVERLAPPED = 0x40000000; //dwFlagsAndAttributes
internal const UInt32 OPEN_EXISTING = 3; //dwCreationDisposition
// Constants pris de WINNT.H
internal const UInt32 GENERIC_READ = 0x80000000; //dwDesiredAccess
internal const UInt32 GENERIC_WRITE = 0x40000000;
internal const UInt32 READ_WRITE = GENERIC_READ | GENERIC_WRITE;
#endregion
#region Imports
/// <summary>
/// Creer ou ouvre l'objet et retourne un handle, qui peut кtre utilisй
/// pour acceder а l'objet
/// </summary>
[DllImport("kernel32.dll", SetLastError=true)]
private static extern IntPtr CreateFile
(
String lpFileName,
UInt32 dwDesiredAccess,
UInt32 dwShareMode,
IntPtr lpSecurityAttributes,
UInt32 dwCreationDisposition,
UInt32 dwFlagsAndAttributes,
IntPtr hTemplateFile
);
/// <summary>
/// Ferme le handle ouvert de l'objet
/// </summary>
[DllImport("kernel32.dll")]
private static extern Boolean CloseHandle
(
IntPtr hObject
);
/// <summary>
/// Lire les donnйes depuis un stream. Commence а la position
/// indiquйe par le pointeur de stream.
/// </summary>
[DllImport("kernel32.dll", SetLastError=true)]
private static extern Boolean ReadFile
(
IntPtr hFile,
[Out] Byte[] lpBuffer,
UInt32 nNumberOfBytesToRead,
out UInt32 nNumberOfBytesRead,
IntPtr lpOverlapped
);
/// <summary>
/// Ecrire les donnйes dans un stream.
/// </summary>
[DllImport("kernel32.dll", SetLastError=true)]
private static extern Boolean WriteFile
(
IntPtr fFile,
Byte[] lpBuffer,
UInt32 nNumberOfBytesToWrite,
out UInt32 lpNumberOfBytesWritten,
IntPtr lpOverlapped
);
#endregion
потом с этими функциями работаешь как в винде:
/// <summary>
/// Ecrire les donnйes dans le port
/// </summary>
/// <param name="buf">Tampon а йcrire</param>
/// <param name="nToSend">Numиro de byte а йcrire</param>
/// <param name="nSent">Nombre d'octets envoyйs</param>
/// <param name="ovlap">Overlapped</param>
/// <returns>true si succes, false sinon</returns>
public bool Write(byte[] buf, uint nToSend, out uint nSent)
{
// Send data buffer.
bool status = WriteFile(this.port, buf, nToSend, out nSent, IntPtr.Zero);
if (!status)
{
this.fault="Error WriteFile(). Error code: " + Marshal.GetLastWin32Error().ToString();
}
else
{
this.fault="OK";
}
return status;
}