C# and .NET New

C# Modbus TCP and RTU Library for .NET

Read and write PLCs, drives and meters from C#, or serve your own data as a Modbus slave, over Ethernet or RS-485.

Modbus TCP and Modbus RTU
Client and server
Float32, Int32 and strings in any word order
Thread-safe blocking calls

Included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, or as the standalone sgcIndustrial pack.

Read and write a device in C# → · Modbus FAQ →

C# Modbus TCP client
using esegece.sgcWebSockets;

var modbus = new TsgcModbusTCPClient();
modbus.Host = "192.168.1.50";
modbus.Port = 502;
modbus.Active = true;

ushort[] registers = modbus.ReadHoldingRegisters(0, 10);  // FC 03
float temperature = modbus.ReadFloat32(200);               // 2 registers
modbus.WriteSingleCoil(5, true);                           // FC 05

Modbus clients and servers for .NET

Four components, one API for TCP and RTU, a thread-safe data model behind the servers.

The C# Modbus library in sgcWebSockets .NET lives in the esegece.sgcIndustrial package, namespace esegece.sgcWebSockets. TsgcModbusTCPClient and TsgcModbusRTUClient are Modbus masters that poll devices; TsgcModbusTCPServer and TsgcModbusRTUServer are Modbus slaves that answer SCADA systems, HMIs and other masters from a TsgcModbusDataModel. The serial line is a TsgcSerialPort from the same package, built on System.IO.Ports.

Both clients share TsgcModbusClient_Base, so a method that reads a register over Ethernet reads it over RS-485 too. Each call blocks until the answer arrives or Timeout expires, returns plain .NET arrays (ushort[] for registers, bool[] for coils) and throws a typed exception when the device reports an error. The package targets .NET 8, .NET 9, .NET 10 and .NET Standard 2.0.

Function codes

01 to 08, 15, 16, 22, 23 and 43/14, one method each.

Typed values

ReadFloat32, ReadInt32, ReadUInt32, ReadString and their write twins, with WordOrder for the four register layouts.

Modbus TCP

Port 502 by default, with optional TLS, an HTTP or SOCKS proxy and automatic reconnect.

Modbus RTU

RS-232 and RS-485 with 3.5 character framing, CRC checks and broadcast writes.

Modbus in C#, step by step

Reference the esegece.sgcIndustrial package, then pick the transport. Every sample on this page compiles against .NET 8.

using esegece.sgcWebSockets;

var modbus = new TsgcModbusTCPClient();
modbus.Host = "192.168.1.50";
modbus.Port = 502;
modbus.UnitId = 1;
modbus.Timeout = 2000;            // ms per attempt
modbus.Retries = 2;               // extra attempts after a timeout
modbus.WatchDog.Enabled = true;   // reconnect after a network drop
modbus.OnError += (sender, error) => Console.WriteLine("#error: " + error);
modbus.Active = true;

ushort[] registers = modbus.ReadHoldingRegisters(0, 10);       // FC 03
bool[] coils = modbus.ReadCoils(0, 8);                         // FC 01
Console.WriteLine("HR0 = " + registers[0] + ", coil 0 = " + coils[0]);

modbus.WriteSingleRegister(100, 1234);                         // FC 06
modbus.WriteMultipleRegisters(110, new ushort[] { 1, 2, 3 });  // FC 16
modbus.WriteSingleCoil(5, true);                               // FC 05
modbus.WordOrder = TsgcModbusWordOrder.mwoCDAB;   // low word first
float temperature = modbus.ReadFloat32(200);       // 2 holding registers
int counter = modbus.ReadInt32(202);
string name = modbus.ReadString(300, 8);           // 8 registers, 16 characters
Console.WriteLine($"{name}: {temperature:F1} C, {counter} cycles");

modbus.WriteFloat32(210, 21.5f);
modbus.WriteUInt32(212, 3000000000);

// explicit unit id, for a gateway with several devices behind it
float flow = modbus.ReadInputFloat32(7, 0);        // unit 7, FC 04
Console.WriteLine("flow = " + flow);

try
{
    modbus.ReadHoldingRegisters(9000, 4);
}
catch (EsgcModbusException e)   // the device answered with an exception
{
    Console.WriteLine($"exception {e.ExceptionCode}, function {e.FunctionCode}");
}
catch (EsgcModbusTimeout e)     // no answer after Retries + 1 attempts
{
    Console.WriteLine(e.Message);
}
using esegece.sgcWebSockets;

var port = new TsgcSerialPort();
port.Port = "COM3";                              // "/dev/ttyUSB0" on Linux
port.BaudRate = 19200;
port.Parity = TsgcSerialParity.spEven;           // 8E1, the Modbus RTU default
port.Open();

var rtu = new TsgcModbusRTUClient();
rtu.SerialPort = port;
rtu.UnitId = 17;                                 // slave address
rtu.Timeout = 500;
rtu.Retries = 1;

ushort[] values = rtu.ReadInputRegisters(0, 4);  // FC 04
byte status = rtu.ReadExceptionStatus();         // FC 07
Console.WriteLine($"IR0 = {values[0]}, status = {status}");

rtu.WriteSingleRegister(0, 10, 500);             // unit 0: broadcast, no reply
using esegece.sgcWebSockets;

var server = new TsgcModbusTCPServer();
server.Port = 502;
server.UnitId = 0;                                  // answer every unit id
server.DataModel.HoldingRegisterCount = 1000;
server.DataModel.SetHoldingRegister(0, 42);
server.DataModel.SetCoil(0, true);
server.DataModel.VendorName = "My Company";         // FC 43/14 identification
server.DataModel.ProductCode = "GW-100";

var random = new Random();

// runs on the connection thread, before the table is read
server.OnReadRequest += (object sender, byte unitId, byte functionCode,
    ushort address, ushort count, ref byte exceptionCode) =>
{
    if (functionCode == sgcModbus_Classes.CS_MODBUS_FC_READ_INPUT_REGISTERS)
        server.DataModel.SetInputRegister(0, (ushort)random.Next(1000));
};

// registers 0..9 are read only
server.OnWriteRequest += (object sender, byte unitId, byte functionCode,
    ushort address, ushort count, ref bool[] bits, ref ushort[] registers,
    ref byte exceptionCode) =>
{
    if (registers.Length > 0 && address < 10)
        exceptionCode = sgcModbus_Classes.CS_MODBUS_EX_ILLEGAL_DATA_ADDRESS;
};

server.Active = true;
Console.ReadLine();

The calls are synchronous. In a WinForms, WPF or ASP.NET application, run a polling loop on a worker thread or inside Task.Run; the client is thread safe, so several tasks can share one connection.

Supported Modbus function codes

The client checks quantities against the specification before anything is sent; the servers answer every code in this table.

FCFunctionC# method
01Read CoilsReadCoils
02Read Discrete InputsReadDiscreteInputs
03Read Holding RegistersReadHoldingRegisters, ReadInt32, ReadUInt32, ReadFloat32, ReadString
04Read Input RegistersReadInputRegisters, ReadInputInt32, ReadInputUInt32, ReadInputFloat32
05Write Single CoilWriteSingleCoil
06Write Single RegisterWriteSingleRegister
07Read Exception Status (serial line)ReadExceptionStatus on the RTU client
08Diagnostics (serial line)Diagnostics on the RTU client
15Write Multiple CoilsWriteMultipleCoils
16Write Multiple RegistersWriteMultipleRegisters, WriteInt32, WriteUInt32, WriteFloat32, WriteString
22Mask Write RegisterMaskWriteRegister
23Read/Write Multiple RegistersReadWriteMultipleRegisters
43/14Read Device IdentificationReadDeviceIdentification with TsgcModbusDeviceIdCode basic, regular, extended or specific

A Modbus master built for production

Word order

TsgcModbusWordOrder.mwoABCD is big endian, the Modbus default. mwoCDAB puts the low word first, mwoBADC swaps the bytes in each register and mwoDCBA is fully little endian. Strings pack two characters per register.

Thread safe

One transaction runs at a time per client, under a lock that covers all its retries. On TCP the reply is matched by the receive thread and handed to the waiting call, so a call from a UI thread cannot deadlock.

Timeouts and retries

Timeout is the wait per attempt, Retries the extra attempts. A TCP retry uses a new transaction id, and stale or duplicate answers are dropped.

Typed exceptions

EsgcModbusException carries ExceptionCode and FunctionCode, EsgcModbusTimeout reports a missing answer, and EsgcModbusError covers closed connections, port problems and RTU CRC errors.

Gateways and unit ids

Every method has an overload with a leading byte aUnitId, so one TCP connection to a gateway reaches every device behind it.

TLS, proxy and reconnect

TLS, TLSOptions, Proxy and WatchDog are passed to the sgcWebSockets TCP client underneath, so Modbus TCP gets the same TLS stack, proxy support and auto-reconnect as the rest of the library.

RTU framing

The RTU client waits for the 3.5 character silence before sending, reads the reply by its expected length, checks the CRC of every frame and ignores frames from other slave addresses. Unit id 0 sends a broadcast write and waits TurnaroundDelay instead of an answer.

RS-485 direction

With RtsControl = TsgcSerialRtsControl.srcToggle the serial port raises RTS for each write and drops it when the output buffer has drained. In .NET this is timed in software, so for strict bus timing prefer an adapter with automatic direction control.

Events

OnConnect, OnDisconnect and OnError are raised through NotifyEvents, in the order they happened. A failed connect does not throw: it raises OnError and Active stays false.

Modbus TCP and RTU servers in C#

Build a gateway that exposes database or cloud values to a SCADA system, a simulator to test HMI screens without hardware, or the Modbus interface of your own device. Each server owns a TsgcModbusDataModel with the four tables (coils, discrete inputs, holding registers and input registers, 10,000 entries each by default and up to 65,536), the identification strings for FC 43/14 and the exception status for FC 07. Every member of the data model is thread safe.

OnReadRequest runs before a table is read, so it can refresh values or answer with an exception code. OnWriteRequest receives the values before they are stored and can change them or reject the write, leaving the tables untouched. Both run in the server thread that handles the request (the TCP connection or the RTU frame reader) with no lock held.

TsgcModbusTCPServer

Many concurrent connections, requests answered in arrival order, split requests reassembled and malformed headers closing the connection with OnError. UnitId = 0 answers any unit id. Bindings select the endpoints, Port = 0 picks a free port, and OnClientConnect and OnClientDisconnect report peers.

TsgcModbusRTUServer

Answers as slave UnitId (1 to 247) on a TsgcSerialPort, frames requests by length and the 3.5 character silence, ignores bad CRCs and other addresses, and executes broadcast writes without replying.

Tested both ways

The .NET client and server pass the same interoperability checks against pymodbus over TCP and against the sgcWebSockets Delphi Modbus components, 35 out of 35 in each direction.

Part of sgcWebSockets Enterprise

The Modbus and serial port components are included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, as the esegece.sgcIndustrial package next to the other sgcWebSockets .NET packages. Compare the editions on the pricing page (.NET tab) or in the .NET feature matrix.

C# Modbus questions

Create a TsgcModbusTCPClient, set Host, Port and UnitId, set Active = true and call ReadHoldingRegisters(address, count). It returns a ushort[] with one value per register. Addresses are zero based, as they travel on the wire.

Call ReadFloat32(address) for holding registers or ReadInputFloat32(address) for input registers. If the number looks wrong, the device stores the two registers in another order: set WordOrder to mwoCDAB, mwoBADC or mwoDCBA.

Yes. Open a TsgcSerialPort on the RS-485 adapter and assign it to TsgcModbusRTUClient.SerialPort or TsgcModbusRTUServer.SerialPort. Use an adapter with automatic direction control, or set RtsControl to srcToggle for adapters switched by RTS.

Yes. Create a TsgcModbusTCPServer, fill DataModel with SetHoldingRegister, SetCoil and the other setters, and set Active = true. Handle OnReadRequest and OnWriteRequest to compute values on demand or reject writes with a Modbus exception code.

No, the client methods are synchronous and thread safe. Call them from a worker thread or wrap them in Task.Run; several threads or tasks can share one client, and each call waits for its own answer.

The esegece.sgcIndustrial package targets .NET 8, .NET 9, .NET 10 and .NET Standard 2.0. The serial port uses System.IO.Ports, so Modbus RTU needs a platform where that package can open serial ports.

The Modbus and serial port components are included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, or as the standalone sgcIndustrial pack.

More on sgcWebSockets .NET

Industrial components

Serial port, Modbus and OPC UA, with the full component reference.

C# OPC UA client

Read, write and subscribe to OPC UA servers from the same .NET application, next to the Modbus devices.

C# MQTT client

Publish Modbus readings to an MQTT broker from the same application.

C# WebSocket library

WebSocket client and server for dashboards that show live device data.

Also for Delphi and C++Builder

The same Modbus components, with the same class names and methods, for Delphi 7 to Delphi 13.

Best value: All-AccessEvery eSeGeCe product, Premium Support included, from €1,059/year.
See All-Access pricing

Read your first Modbus register from C#

Included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, or as the standalone sgcIndustrial pack.