C# and .NET New

C# OPC UA Client Library for .NET

Browse, read, write and subscribe to the OPC UA servers of PLCs, SCADA systems and gateways from C#, over a signed and encrypted opc.tcp connection.

OPC UA binary over opc.tcp
Sign and SignAndEncrypt up to Aes256_Sha256_RsaPss
Data change and event subscriptions
Anonymous, user name and X.509 identities

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

Read and subscribe in C# → · OPC UA FAQ →

C# OPC UA client
using System;
using esegece.sgcWebSockets;

var opcua = new TsgcOPCUAClient();
opcua.EndpointUrl = "opc.tcp://192.168.1.60:4840";
opcua.Connect();
Console.WriteLine(opcua.ReadValue("ns=2;s=Line1.Temperature"));
opcua.WriteValue("ns=2;s=Line1.Setpoint", 75.5);
opcua.Disconnect();

An OPC UA client for .NET applications

Secure channel, session, services and subscriptions in one class, with the same API as the Delphi component.

The C# OPC UA client in sgcWebSockets .NET is TsgcOPCUAClient, part of the esegece.sgcIndustrial package, namespace esegece.sgcWebSockets. Set EndpointUrl, choose SecurityPolicy and SecurityMode, call Connect and work with node ids such as ns=2;s=Line1.Speed. ReadValue returns the value as a plain .NET object (typed arrays, double[,] for a matrix), and WriteValue reads the data type of the node first so the value is encoded as the server expects.

Every service call is synchronous and throws EsgcOPCUAError, whose StatusCode holds the OPC UA status code, when it fails. Subscriptions push data changes and events to your handlers through OnDataChange and OnEvent. The package targets .NET 8, .NET 9, .NET 10 and .NET Standard 2.0.

Services

GetEndpoints, Browse, BrowseNext, TranslateBrowsePath, Read, Write and Call.

Subscriptions

Data change items with deadband and queue size, event items with select and where clauses.

Security

Basic256Sha256, Aes128_Sha256_RsaOaep and Aes256_Sha256_RsaPss in Sign or SignAndEncrypt mode.

Identities

Anonymous, user name and password, or an X.509 user certificate.

OPC UA in C#, step by step

Reference the esegece.sgcIndustrial package, connect, then read, browse or subscribe. Every sample on this page compiles against .NET 8.

using System;
using esegece.sgcWebSockets;

var opcua = new TsgcOPCUAClient();
opcua.EndpointUrl = "opc.tcp://192.168.1.60:4840";
opcua.Connect();
try
{
    Console.WriteLine("Speed: " + opcua.ReadValue("ns=2;s=Line1.Speed"));
    // write with an explicit built-in type
    opcua.WriteValue("ns=2;s=Line1.Mode", (ushort)2, TsgcOPCUABuiltInType.uabtUInt16);
}
catch (EsgcOPCUAError e)
{
    Console.WriteLine($"Status 0x{e.StatusCode:X8}: {e.Message}");
}
finally
{
    opcua.Disconnect();
}
using System;
using esegece.sgcWebSockets;
using static esegece.sgcWebSockets.sgcOPCUA_Types;

var opcua = new TsgcOPCUAClient();
opcua.EndpointUrl = "opc.tcp://192.168.1.60:4840";
opcua.Connect();
// i=85 is the Objects folder
foreach (TsgcOPCUAReferenceDescription item in opcua.Browse("i=85"))
    Console.WriteLine(item.DisplayName.Text + " = " + sgcOPCUANodeIdToString(item.NodeId.NodeId));
// resolve a browse path to a node id
TsgcOPCUANodeId speed = opcua.TranslateBrowsePath("i=85", "/2:Line1/2:Speed");
Console.WriteLine(sgcOPCUANodeIdToString(speed));
// call a method with two Int32 arguments
TsgcOPCUAVariant[] outputs = opcua.Call("ns=2;s=Methods", "ns=2;s=Methods.Add", new[] {
    sgcOPCUAVariantSimple(TsgcOPCUABuiltInType.uabtInt32, 2),
    sgcOPCUAVariantSimple(TsgcOPCUABuiltInType.uabtInt32, 3) });
Console.WriteLine("Result: " + outputs[0].Value);
opcua.Disconnect();
using System;
using esegece.sgcWebSockets;
using static esegece.sgcWebSockets.sgcOPCUA_Encoding;

class LineMonitor
{
    public void Start(TsgcOPCUAClient aClient)
    {
        aClient.OnDataChange += OnOPCUADataChange;
        aClient.OnEvent += OnOPCUAEvent;
        TsgcOPCUASubscription subscription = aClient.CreateSubscription(500);
        // report changes larger than 0.5 only
        aClient.AddMonitoredItem(subscription, "ns=2;s=Line1.Temperature", 250, 1, true,
            TsgcOPCUADeadbandType.uadbtAbsolute, 0.5);
        // i=2253 is the Server object, which reports the events of the whole server
        aClient.AddEventMonitoredItem(subscription, "i=2253", new[] { "Message", "Severity", "SourceName" });
    }

    void OnOPCUADataChange(object Sender, TsgcOPCUASubscription aSubscription,
        TsgcOPCUAMonitoredItem aMonitoredItem, TsgcOPCUADataValue aValue)
    {
        Console.WriteLine("Temperature: " + aValue.Value.Value);
    }

    void OnOPCUAEvent(object Sender, TsgcOPCUASubscription aSubscription,
        TsgcOPCUAMonitoredItem aMonitoredItem, TsgcOPCUAVariant[] aEventFields)
    {
        // the fields arrive in the order of the select clauses
        Console.WriteLine(sgcOPCUAVariantToValue(aEventFields[2]) + " (" +
            sgcOPCUAVariantToValue(aEventFields[1]) + "): " + sgcOPCUAVariantToValue(aEventFields[0]));
    }
}
using System.IO;
using System.Linq;
using esegece.sgcWebSockets;

class SecureLine
{
    // DER bytes of the server certificate you trust
    readonly byte[] FTrusted = File.ReadAllBytes(@"C:\pki\trusted\server.der");

    public TsgcOPCUAClient Connect()
    {
        var opcua = new TsgcOPCUAClient();
        opcua.EndpointUrl = "opc.tcp://192.168.1.60:4840";
        opcua.SecurityPolicy = TsgcOPCUASecurityPolicy.opcspAes256_Sha256_RsaPss;
        opcua.SecurityMode = TsgcOPCUAMessageSecurityMode.opcsmSignAndEncrypt;
        // no certificate files set: the application certificate is created in memory
        // X.509 user identity
        opcua.Authentication.AuthenticationType = TsgcOPCUAAuthenticationType.opcatCertificate;
        opcua.Authentication.CertificateFile = @"C:\pki\user\operator.der";
        opcua.Authentication.PrivateKeyFile = @"C:\pki\user\operator.pem";
        opcua.OnValidateServerCertificate += OnOPCUAValidateServerCertificate;
        opcua.WatchDog.Enabled = true;   // reconnect after a network drop
        opcua.Connect();
        return opcua;
    }

    void OnOPCUAValidateServerCertificate(object Sender, byte[] aCertificate, ref bool aAccept)
    {
        aAccept = aCertificate != null && aCertificate.SequenceEqual(FTrusted);
    }
}

The service calls are synchronous. In a WinForms, WPF or ASP.NET application, call them from a worker thread or inside Task.Run. The subscription events are raised through NotifyEvents: on the UI thread when there is one, otherwise in order on the thread pool.

Supported OPC UA services

Simple overloads take node id strings; full overloads take the request classes of the specification.

Service setServiceC# method
DiscoveryGetEndpointsGetEndpoints
ViewBrowse, BrowseNextBrowse, BrowseNext
ViewTranslateBrowsePathsToNodeIdsTranslateBrowsePath
AttributeReadRead, ReadValue
AttributeWriteWrite, WriteValue
MethodCallCall
SubscriptionCreateSubscription, DeleteSubscriptions, SetPublishingModeCreateSubscription, DeleteSubscription, SetPublishingMode
MonitoredItemCreateMonitoredItems, ModifyMonitoredItems, DeleteMonitoredItemsAddMonitoredItem, AddEventMonitoredItem, ModifyMonitoredItem, RemoveMonitoredItem
SubscriptionPublish, Republish, TransferSubscriptionsDone by the client: OnDataChange, OnEvent, OnKeepAlive, WatchDog

An OPC UA client built for production

Publish loop handled

The client keeps enough Publish requests in flight, acknowledges every notification, asks the server to republish a message that went missing and drops duplicates, so your handlers see each value once.

Deadband and queues

AddMonitoredItem sets the sampling interval, the queue size and an absolute or percent deadband per node. ModifyMonitoredItem changes them later and SetPublishingMode pauses a subscription.

Events and alarms

AddEventMonitoredItem returns the event fields you select, such as Message, Severity and SourceName, filtered by an optional where clause.

Certificates

The application certificate is loaded from DER or PEM files, created and saved on the first connect, or created in memory. A server certificate is rejected unless OnValidateServerCertificate accepts it.

Automatic reconnect

After a network drop, WatchDog first reactivates the same session and republishes the notifications that were missed. If the session is gone it opens a new one and transfers or recreates the subscriptions. OnReconnect tells which path was taken, and your subscription objects stay valid.

Same API as Delphi

Class, property, method and event names match the Delphi and C++Builder component, so a team can share one design across both platforms.

Part of sgcWebSockets Enterprise

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

It is tested against a reference server built on asyncua, an independent open-source OPC UA implementation: all eleven endpoints (every policy and mode), the three identity types, browsing with continuation points, reading 18 built-in types with arrays and a matrix, method calls, deadband and event subscriptions and a two-minute publish run without a lost or duplicated message.

C# OPC UA questions

Create a TsgcOPCUAClient, set EndpointUrl, call Connect() and then ReadValue("ns=2;s=Line1.Speed"). It returns an object with the .NET type of the value. Read reads several nodes and attributes in one call.

Call CreateSubscription with the publishing interval, add nodes with AddMonitoredItem and handle OnDataChange. A deadband on each item keeps small changes out of your handler.

Basic256Sha256, Aes128_Sha256_RsaOaep and Aes256_Sha256_RsaPss in Sign or SignAndEncrypt mode, plus the deprecated Basic128Rsa15 and Basic256 for older servers, and None for test benches.

Handle OnValidateServerCertificate and set aAccept to true only for the certificates you trust, for example by comparing the DER bytes with a copy you saved. Without the handler every secured connection is rejected, unless AutoAcceptServerCertificate is set for testing.

The client raises OnError and OnDisconnect. With WatchDog.Enabled = true it then retries every WatchDog.Interval seconds (10 by default, WatchDog.Attempts 0 means no limit). It reactivates the same session when the server still has it, otherwise it opens a new session and transfers or recreates the subscriptions. OnReconnect reports which path was taken, and your subscription objects stay valid.

The esegece.sgcIndustrial package targets .NET 8, .NET 9, .NET 10 and .NET Standard 2.0, so it also runs on .NET Framework 4.8.

The OPC UA client is included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, or as the standalone sgcIndustrial pack. It does not include an OPC UA server, the HTTPS, JSON and WebSocket transports, HistoryRead, PubSub, Reverse Connect and the Global Discovery Server.

More on sgcWebSockets .NET

Industrial components

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

C# Modbus TCP and RTU

Modbus clients and servers for the devices next to your OPC UA servers.

C# MQTT client

Forward OPC UA data changes to an MQTT broker from the same application.

Also for Delphi and C++Builder

The same OPC UA client, with the same class and method names and the same WatchDog reconnect.

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

Read your first OPC UA node from C#

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