Skip to main content

File Transfer (OpcUaFile)

Overview​

OPC UA Part 5 §10 defines the FileType (i=11575) standard object, which exposes 6 methods: Open / Read / Write / Close / GetPosition / SetPosition

OpcUaFile Provides .NET API for stream-based calls. Applicable scenarios:

  • Firmware Updates (PLC / IO / Drive Image Downloads)
  • Upload / Download Recipes
  • Synchronization of Arbitrary File Images

Corresponding section of the standard: Part 5, §10 (FileType).

API​

Methods / PropertiesCategoryReading and WritingNote
new OpcUaFile(ua, fileNodeId)Structure—Bind to a specific FileType Examples; If any parameter is empty, the trade is canceled ArgumentNullException
file.IsOpenPropertiesReadIs it already Open(bool)?
file.FileHandlePropertiesReadHandle allocated by the server (uint0 when not open)
file.FileNodeIdPropertiesReadInstances passed during construction NodeId
file.SizePropertiesReadFile size (ulong); Returns 0 if cannot be read
file.WritablePropertiesReadOn the server side, is it possible to write (bool); and return false if the read fails?
file.UserWritablePropertiesReadWhether the current user has write access (bool, affected ACL by ); returns false if read access is not granted
file.OpenCountPropertiesReadCurrent number of open handles (ushort); Returns 0 if nothing can be read
file.Open(mode)MethodsWriteOpen the handle; return StatusCode; FileHandle / This is valid only IsOpen if successful
file.Close()MethodsWriteClose the handle; return silently if it is not open Good (Dispose will be called)
file.Read(length)MethodsReadRead N bytes, return (StatusCode Status, byte[] Data); empty array = EOF
file.Write(bytes)MethodsWriteWrite a byte; return StatusCode; null / 0 length treated as no-op returns Good
file.GetPosition()MethodsReadReturns (StatusCode Status, ulong Position)
file.SetPosition(pos)MethodsWriteJump to file pointer, return StatusCode
file.DownloadTo(localPath, progress)High-levelReadDownload to a local file with one click, then return StatusCode
file.UploadFrom(localPath, progress)High-levelWriteUpload from a local file with one click, then return StatusCode

Full signature:

public OpcUaFile(DarraOpcUa ua, string fileNodeId);

public bool IsOpen { get; }
public uint FileHandle { get; }
public string FileNodeId { get; }
public ulong Size { get; }
public ushort OpenCount { get; }
public bool Writable { get; }
public bool UserWritable { get; }

public StatusCode Open(FileOpenMode mode);
public StatusCode Close();
public (StatusCode Status, byte[] Data) Read(int length);
public StatusCode Write(byte[] data);
public (StatusCode Status, ulong Position) GetPosition();
public StatusCode SetPosition(ulong pos);
public StatusCode DownloadTo(string localPath, IProgress<(ulong done, ulong total)> progress = null);
public StatusCode UploadFrom(string localPath, IProgress<(ulong done, ulong total)> progress = null);
public void Dispose();

DownloadTo / UploadFrom is progress IProgress<(ulong done, ulong total)>; total It could be 0 (When Size the server hasn't provided the value), you need to check for zero before calculating the percentage yourself.

Related Structures:

[Flags]
public enum FileOpenMode : byte
{
Read = 0x01, // Read
Write = 0x02, // Write
EraseExisting = 0x04, // Clear (Must be set along with Write)
Append = 0x08 // Add
}

UploadFrom Pinned to Open FileOpenMode.Write | FileOpenMode.EraseExisting —— Uploading will clear the contents of the original file on the server.。

Code Example​

using System;
using DarraOpcUa_Client;

using var ua = new DarraOpcUa("opc.tcp://device:4840");
ua.Connect();

// 1) One-click firmware download
using (var file = new OpcUaFile(ua, "ns=2;s=Firmware.Image"))
{
Console.WriteLine($"Size = {file.Size} bytes");
var rc = file.DownloadTo(@"C:\dl\firmware.bin",
new Progress<(ulong done, ulong total)>(p =>
{
// total may be 0 (the server did not provide a Size), so you must first check for zero.
double pct = p.total == 0 ? 0 : (double)p.done * 100 / p.total;
Console.Write($"\r{pct:F0}% ({p.done}/{p.total})");
}));
if (rc != StatusCode.Good) Console.WriteLine($"\n下载失败: {rc}");
}

// 2) Upload a recipe with one click (Select "Write" |EraseExisting "Open"; this will clear the original content on the server)
using (var f2 = new OpcUaFile(ua, "ns=2;s=Recipe.Current"))
{
var rc = f2.UploadFrom(@"C:\recipes\new.csv");
if (rc != StatusCode.Good) Console.WriteLine($"上传失败: {rc}");
}

// 3) Manual stream reading (custom processing of large files in chunks)
using (var f3 = new OpcUaFile(ua, "ns=2;s=Logs.Current"))
{
var rcOpen = f3.Open(FileOpenMode.Read);
if (rcOpen == StatusCode.Good)
{
while (true)
{
var (st, chunk) = f3.Read(4096);
if (st != StatusCode.Good || chunk == null || chunk.Length == 0) break;
ProcessChunk(chunk); // The application's own processing function
}
f3.Close();
}
}

Error Handling​

OpcUaFile methods never throw OpcUaException — every exception is folded into a StatusCode and returned. Both business-level and transport-level failures come back as return values:

  • Invalid argument / Not opened → Returns raw 0x80AB0000 (BadInvalidArgument)
  • Other Exceptions → Returns raw 0x80020000 (BadInternalError)
  • Server rejection → Returned as-is by the server StatusCode

The only exception that will be thrown is a construction-phase exception ( ArgumentNullException ua or a null fileNodeId value).

The two raw codes are not in the enumeration StatusCode.

BadInvalidArgument (0x80AB0000) and BadInternalError (0x80020000) have no corresponding members in the enumeration StatusCode. When comparing (StatusCode)0x80AB0000u, use, not StatusCode.BadInvalidArgument (otherwise it won't compile).

using Exit / Exceptional Path → Automatic Close Open Handles (Implementation IDisposable, Idempotent).

Implementation Notes​

  • Default block size 4 KB (most servers are limited to 8 KB or less; allow for some leeway)
  • ByteString Lossless transmission, preserved 0x00—0xFF full bytes
  • Method Resolution: Automatically resolves the method of a file instance; this also works when the server exposes only standard class-level FileType methods.
  • DownloadTo Judged by “a single read operation returning less than one block (default 4 KB)” — EOF if the server returns a short read in the middle of a file, it will be treated as EOF Early Termination. If you need to download a large file, we recommend that you use Open(Read) + Read(4096) + Size to verify the data yourself, or download it in segments using SetPosition.

Best Practices​

  • Always use using — A "Close" leak causes the server's handle table to leak
  • Progress Callback Thread UI — Progress<T> By default, it captures the current SynchronizationContext; for WPF/WinForms callers, simply construct it on the UI thread.
  • For large files, consider retrying in segments — The upper layer creates a checkpoint at each 4KB block boundary; if the network connection is lost, the data is transmitted later.
  • Do not access the same file handle concurrently — One Open corresponds to one serial stream

Cross-Language Comparison​

C#PythonJavaC++RustC
OpcUaFileOpcUaFileOpcUaFileOpcUaFileOpcUaFileDarraUa_OpcUaFile_*
DownloadTodownload_todownloadToDownloadTodownload_toDarraUa_OpcUaFile_DownloadTo
UploadFromupload_fromuploadFromUploadFromupload_fromDarraUa_OpcUaFile_UploadFrom

Next Step​