Skip to main content

Read / Write

Prerequisite Reading
  • 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.

ParametersTypeDefaultNote
nodeIdstring—NodeId String (i=2258 / ns=2; s=...)
attributeAttributeIdValue (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.

ReadMany The Semantics of Failure
  • 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 DataValue belongs to the caller, Must using / 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 failures use return values, but exceptions are still thrown.

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 exception OpcUaException

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​

FieldTypeNote
ValueVariantActual value
StatusStatusCodeGood / Bad* / Uncertain*
IsGoodboolIs it Good?
SourceTimestampDateTime?Data Source Timestamp
ServerTimestampDateTime?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​

IdNameNote
1NodeIdNode ID
2NodeClassNode Categories
3BrowseNameBrowse Name
4DisplayNameDisplay Name
5DescriptionDescription
13ValueVariable Value (Default)
14DataTypeData Types NodeId
17AccessLevelAccess permission bits
20HistorizingIs history being recorded?
21ExecutableIs the Method Executable?

Best Practices​

  • Lot Priority: Use commas to monitor multiple tags ReadMany; do not use a loop Read (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: DataValue Implement 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 Read once every 1 second; instead, use Subscription DataChanged Event (Server-Side Push)

Next Step​