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 / Properties | Category | Reading and Writing | Note |
|---|---|---|---|
| new OpcUaFile(ua, fileNodeId) | Structure | — | Bind to a specific FileType Examples; If any parameter is empty, the trade is canceled ArgumentNullException |
| file.IsOpen | Properties | Read | Is it already Open(bool)? |
| file.FileHandle | Properties | Read | Handle allocated by the server (uint0 when not open) |
| file.FileNodeId | Properties | Read | Instances passed during construction NodeId |
| file.Size | Properties | Read | File size (ulong); Returns 0 if cannot be read |
| file.Writable | Properties | Read | On the server side, is it possible to write (bool); and return false if the read fails? |
| file.UserWritable | Properties | Read | Whether the current user has write access (bool, affected ACL by ); returns false if read access is not granted |
| file.OpenCount | Properties | Read | Current number of open handles (ushort); Returns 0 if nothing can be read |
| file.Open(mode) | Methods | Write | Open the handle; return StatusCode; FileHandle / This is valid only IsOpen if successful |
| file.Close() | Methods | Write | Close the handle; return silently if it is not open Good (Dispose will be called) |
| file.Read(length) | Methods | Read | Read N bytes, return (StatusCode Status, byte[] Data); empty array = EOF |
| file.Write(bytes) | Methods | Write | Write a byte; return StatusCode; null / 0 length treated as no-op returns Good |
| file.GetPosition() | Methods | Read | Returns (StatusCode Status, ulong Position) |
| file.SetPosition(pos) | Methods | Write | Jump to file pointer, return StatusCode |
| file.DownloadTo(localPath, progress) | High-level | Read | Download to a local file with one click, then return StatusCode |
| file.UploadFrom(localPath, progress) | High-level | Write | Upload 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).
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.
DownloadToJudged 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 useOpen(Read)+Read(4096)+Sizeto verify the data yourself, or download it in segments usingSetPosition.
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# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| OpcUaFile | OpcUaFile | OpcUaFile | OpcUaFile | OpcUaFile | DarraUa_OpcUaFile_* |
| DownloadTo | download_to | downloadTo | DownloadTo | download_to | DarraUa_OpcUaFile_DownloadTo |
| UploadFrom | upload_from | uploadFrom | UploadFrom | upload_from | DarraUa_OpcUaFile_UploadFrom |