Read / Write
- Data Types Variant and DataValue It is the foundation of all reading and writing.
- For frequent access to the same node, please use RegisterNodes Accelerate.
- For real-time change notifications Subscription Rather than a Read loop.
Read
public DataValue Read(string nodeId, AttributeId attribute = AttributeId.Value);
Read the specified Attribute from a single node.
| Parameters | Type | Default | Note |
|---|---|---|---|
| nodeId | string | — | NodeId String (i=2258 / ns=2; s=...) |
| attribute | AttributeId | Value (13) | Properties to Read |
Returns: DataValue (Implementation IDisposable, Must use using)
Exception: OpcUaException (BadNodeIdUnknown / BadNotReadable / BadCommunicationError / ...)
// Read Value
using var dv = ua.Read("ns=2;s=Temperature");
Console.WriteLine(dv.Value.AsDouble); // AsDouble Returns a double? (null if the types don't match); passing a double directly as an argument will result in a compilation error.
// Read DisplayName
using var dn = ua.Read("ns=2;s=Temperature", AttributeId.DisplayName);
Console.WriteLine(dn.Value.AsString);
ReadMany
Batch by Attribute
public IReadOnlyList<DataValue> ReadMany(
IReadOnlyList<string> nodeIds,
AttributeId attribute = AttributeId.Value);
Read the same attribute from multiple nodes in a single RPC batch.
var nodes = new[] { "ns=2;s=T1", "ns=2;s=T2", "ns=2;s=T3" };
var values = ua.ReadMany(nodes);
for (int i = 0; i < nodes.Length; i++)
{
var dv = values[i]; // If a single item fails, this slot is null.
using (dv) Console.WriteLine($"{nodes[i]} = {(dv == null ? "<null>" : dv.Value.ToString())}");
}
Any NodeId + AttributeId Combination
public IReadOnlyList<DataValue> ReadMany(
IReadOnlyList<(string nodeId, AttributeId attr)> items);
var items = new (string, AttributeId)[]
{
("ns=2;s=T1", AttributeId.Value),
("ns=2;s=T1", AttributeId.DataType),
("ns=2;s=T2", AttributeId.Value),
};
var results = ua.ReadMany(items);
foreach (var dv in results)
using (dv) Console.WriteLine(dv == null ? "<null>" : dv.ToString());
Performance: Batch processing saves N-1 round RPC trips compared to single-read cycles.
- The entire batch of calls failed (the server returned a status other than "Good") → Exception thrown
OpcUaException("ReadMany failed", status); no results were returned. - Single-item failure → This slot appears in the return list as
null, The remaining items are returned as usual - Each returned
DataValuebelongs to the caller, Mustusing/Dispose
Write
public StatusCode Write(string nodeId, Variant value, AttributeId attribute = AttributeId.Value);
Order-writing node.
using var v = new Variant();
v.Double = 42.5;
StatusCode st = ua.Write("ns=2;s=Setpoint", v);
if (st != StatusCode.Good) Console.WriteLine($"Write failed: {st}");
Returns StatusCode (Good / BadNotWritable / BadTypeMismatch / BadUserAccessDenied / ...).
Business-level failure (BadNotWritable / BadTypeMismatch / BadUserAccessDenied etc.) Do not throw exceptions, StatusCode Based on the return value, you must check it; do not assume it is "Good."
However, there are Write two pathsMeeting Sell:
value == null→ArgumentNullException- Session-Level Failure (
BadSessionClosed/BadSessionIdInvalid/BadServerNotConnected/BadConnectionClosed/BadSecureChannelClosed) → Automatically reconnect once and retry; if it still fails, throw an exceptionOpcUaException
If you don't want to write, just use try/catch WriteSafe (Collapse the exception into StatusCode).
Variant Quick Reference for Assignment
Variant Only parameterless constructors; assignments use type setters:
using var v = new Variant();
v.Boolean = true;
v.Int16 = 42;
v.Int32 = 42;
v.Int64 = 42L;
v.Double = 3.14;
v.Float = 3.14f;
v.String = "hello";
v.DateTime = DateTime.UtcNow;
// Array
v.SetDoubleArray(new[] { 1.0, 2.0, 3.0 });
v.SetStringArray(new[] { "a", "b", "c" });
For more information, see Variant Data Types.
DataValue Field Quick Reference
| Field | Type | Note |
|---|---|---|
| Value | Variant | Actual value |
| Status | StatusCode | Good / Bad* / Uncertain* |
| IsGood | bool | Is it Good? |
| SourceTimestamp | DateTime? | Data Source Timestamp |
| ServerTimestamp | DateTime? | Timestamps set by the server |
using var dv = ua.Read("ns=2;s=T1");
if (!dv.IsGood)
{
Console.WriteLine($"Bad value: {dv.Status}");
return;
}
Console.WriteLine($"{dv.Value.AsDouble} @ {dv.SourceTimestamp}");
AttributeId Common Values
| Id | Name | Note |
|---|---|---|
| 1 | NodeId | Node ID |
| 2 | NodeClass | Node Categories |
| 3 | BrowseName | Browse Name |
| 4 | DisplayName | Display Name |
| 5 | Description | Description |
| 13 | Value | Variable Value (Default) |
| 14 | DataType | Data Types NodeId |
| 17 | AccessLevel | Access permission bits |
| 20 | Historizing | Is history being recorded? |
| 21 | Executable | Is the Method Executable? |
Best Practices
- Lot Priority: Use commas to monitor multiple tags
ReadMany; do not use a loopRead(saves N-1 iterations RPC) - Use "Batch" for multiple attributes as well: To read a large number of different attributes from the same node, use the format
ReadMany((nodeId, attr)) - Must Dispose:
DataValueImplement IDisposable; failing to call Dispose will cause a resource leak - Write: Check the return value: Don't assume it's necessarily good
- Use subscriptions for real-time changes: Do not poll with
Readonce every 1 second; instead, useSubscriptionDataChanged Event (Server-Side Push)