Client: make the UaFileInfo constructor public (#4790)

# Description

FileSystemClient hands out UaFileInfo objects only for files it resolves
by path below its root directory. An application that already knows the
NodeId of a FileType object, for example from a reference or a method
result, could not get a UaFileInfo for it because the constructor was
internal, and had to fall back to the raw FileTypeClient proxy.

The constructor is now public and documented, and it rejects a null
segment list. A test creates a UaFileInfo for a known NodeId and reads
its metadata through it.

## Related Issues

None.

## Checklist

- [x] I have signed the
[CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf)
and read the
[CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md)
doc.
- [x] I have added tests that prove my fix is effective or that my
feature works and increased code coverage.
- [x] I have added all necessary documentation.
- [x] I have verified that my changes do not introduce (new) build or
analyzer warnings.
- [x] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed.
- [x] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
This commit is contained in:
Wolfgang Colsman
2026-10-15 03:38:21 -04:00
committed by GitHub
parent 15d0ce7bd5
commit d40843c23a
5 changed files with 272 additions and 4 deletions
+25
View File
@@ -34,6 +34,7 @@ to make remote file-system navigation feel like working with a local disk.
- [Stream a large file](#stream-a-large-file)
- [Create a directory tree and write a file](#create-a-directory-tree-and-write-a-file)
- [Move and delete](#move-and-delete)
- [Use a file known by its NodeId](#use-a-file-known-by-its-nodeid)
- [Path syntax](#path-syntax)
- [Path resolution and caching](#path-resolution-and-caching)
- [Type classification](#type-classification-filetype-vs-filedirectorytype)
@@ -104,6 +105,30 @@ await file.MoveToAsync("/Published/v1.txt");
await fs.DeleteAsync("/Drafts", recursive: true);
```
### Use a file known by its NodeId
A `FileType` NodeId can come from somewhere other than a path below the
root, for example from a reference or a method result. Create the
`UaFileInfo` directly instead of falling back to the raw `FileTypeClient`
proxy:
```csharp
// The containing directory is known: every operation is available and
// the path is the directory's path followed by the BrowseName.
UaDirectoryInfo reports = await fs.GetDirectoryAsync("/Reports");
var report = new UaFileInfo(reports, reportNodeId, new QualifiedName("summary.json"));
await report.RefreshAsync();
await report.DeleteAsync();
// Only the NodeId is known: the file is detached. It can be refreshed,
// opened, read and written, but DeleteAsync, MoveToAsync and CopyToAsync
// throw InvalidOperationException, because those are methods of the
// containing FileDirectoryType.
var result = new UaFileInfo(fs, resultFileNodeId, new QualifiedName("result.bin"));
byte[] bytes = await result.ReadAllBytesAsync();
bool detached = result.IsDetached; // true; Parent is null
```
## Path syntax
Paths use the forward slash `'/'` as the segment separator. Each segment
@@ -777,7 +777,9 @@ namespace Opc.Ua.Client.FileSystem
{
if (target.Parent == null)
{
throw new IOException("Cannot delete the root directory.");
throw target is UaFileInfo { IsDetached: true }
? DetachedFileError(target, "deleted")
: new IOException("Cannot delete the root directory.");
}
// Empty-check before delegating to the server, whose Delete on a
@@ -815,6 +817,13 @@ namespace Opc.Ua.Client.FileSystem
bool copy,
CancellationToken ct)
{
// Reject a detached file before the destination is resolved: the
// operation cannot succeed, and resolving the destination could
// fail first with a misleading error and cost server requests.
if (source is UaFileInfo { IsDetached: true })
{
throw DetachedFileError(source, copy ? "copied" : "moved");
}
QualifiedName[] segments = UaPath.Parse(destPath);
if (segments.Length == 0)
{
@@ -846,7 +855,9 @@ namespace Opc.Ua.Client.FileSystem
ValidateLeafName(newName);
if (source.Parent == null)
{
throw new IOException("Cannot move or copy the root directory.");
throw source is UaFileInfo { IsDetached: true }
? DetachedFileError(source, copy ? "copied" : "moved")
: new IOException("Cannot move or copy the root directory.");
}
NodeId newId;
@@ -1412,7 +1423,7 @@ namespace Opc.Ua.Client.FileSystem
return TryGetQualifiedName(dv.WrappedValue) ?? QualifiedName.Null;
}
private static QualifiedName[] AppendSegment(
internal static QualifiedName[] AppendSegment(
IReadOnlyList<QualifiedName> parent,
QualifiedName name)
{
@@ -1425,6 +1436,15 @@ namespace Opc.Ua.Client.FileSystem
return combined;
}
private static InvalidOperationException DetachedFileError(
UaFileSystemInfo target,
string operation)
{
return new InvalidOperationException(
$"File '{target.Name}' ({target.NodeId}) cannot be {operation} because the directory " +
"that contains it is not known. Create the UaFileInfo with its parent directory instead.");
}
private static void ValidateLeafName(string name)
{
if (string.IsNullOrEmpty(name))
@@ -53,6 +53,69 @@ namespace Opc.Ua.Client.FileSystem
/// </remarks>
public sealed class UaFileInfo : UaFileSystemInfo
{
/// <summary>
/// Creates a handle to the <c>FileType</c> instance with the given
/// NodeId inside a known directory, for a file that is already known
/// by its NodeId rather than by a path below the
/// <see cref="FileSystemClient"/> root.
/// </summary>
/// <remarks>
/// The file belongs to the <see cref="UaFileSystemInfo.Owner"/> of
/// <paramref name="parent"/>, and its path is the path of
/// <paramref name="parent"/> followed by
/// <paramref name="browseName"/>. Every operation, including
/// <see cref="UaFileSystemInfo.DeleteAsync(CancellationToken)"/>,
/// moving and copying, is available.
/// </remarks>
/// <param name="parent">The directory that contains the file.</param>
/// <param name="nodeId">The NodeId of the <c>FileType</c> instance.</param>
/// <param name="browseName">The BrowseName of the file.</param>
/// <exception cref="ArgumentNullException"><paramref name="parent"/>
/// or <paramref name="nodeId"/> is null.</exception>
public UaFileInfo(
UaDirectoryInfo parent,
NodeId nodeId,
QualifiedName browseName)
: this(
(parent ?? throw new ArgumentNullException(nameof(parent))).Owner,
parent,
nodeId,
browseName,
FileSystemClient.AppendSegment(parent.Segments, browseName))
{
}
/// <summary>
/// Creates a handle to a detached <c>FileType</c> instance: a file
/// that is known only by its NodeId, for example from a reference
/// or a method result, and whose containing directory is not known.
/// </summary>
/// <remarks>
/// A detached file can be refreshed, opened, read and written. It
/// cannot be deleted, moved or copied, because these operations
/// are methods of the containing <c>FileDirectoryType</c>; they
/// throw <see cref="InvalidOperationException"/>. Its
/// <see cref="UaFileSystemInfo.Parent"/> is <c>null</c>, and its
/// <see cref="UaFileSystemInfo.Segments"/> contain only
/// <paramref name="browseName"/> because its location below the
/// root of <paramref name="owner"/> is not known. Use
/// <see cref="UaFileInfo(UaDirectoryInfo, NodeId, QualifiedName)"/>
/// when the directory is known.
/// </remarks>
/// <param name="owner">The file system client whose session is used.</param>
/// <param name="nodeId">The NodeId of the <c>FileType</c> instance.</param>
/// <param name="browseName">The BrowseName of the file.</param>
/// <exception cref="ArgumentNullException"><paramref name="owner"/>
/// or <paramref name="nodeId"/> is null.</exception>
public UaFileInfo(
FileSystemClient owner,
NodeId nodeId,
QualifiedName browseName)
: this(owner, parent: null, nodeId, browseName, [browseName])
{
IsDetached = true;
}
internal UaFileInfo(
FileSystemClient owner,
UaDirectoryInfo? parent,
@@ -70,6 +133,15 @@ namespace Opc.Ua.Client.FileSystem
/// <inheritdoc/>
public override bool IsDirectory => false;
/// <summary>
/// <c>true</c> when the file was created for a known NodeId
/// without its containing directory; see
/// <see cref="UaFileInfo(FileSystemClient, NodeId, QualifiedName)"/>.
/// Deleting, moving and copying a detached file throw
/// <see cref="InvalidOperationException"/>.
/// </summary>
public bool IsDetached { get; }
/// <summary>The cached <c>Size</c> property in bytes.</summary>
public ulong Size { get; private set; }
@@ -67,7 +67,8 @@ namespace Opc.Ua.Client.FileSystem
public FileSystemClient Owner { get; }
/// <summary>
/// The parent directory; <c>null</c> only for the root.
/// The parent directory; <c>null</c> for the root and for a
/// detached file (see <see cref="UaFileInfo.IsDetached"/>).
/// </summary>
public UaDirectoryInfo? Parent { get; }
@@ -29,6 +29,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
@@ -122,6 +123,155 @@ namespace Opc.Ua.Client.Tests.FileSystem
Assert.That(closes, Is.EqualTo(1));
}
[Test]
public void FileInfoPublicConstructorsTakeNoCollectionParameter()
{
System.Reflection.ConstructorInfo[] constructors = typeof(UaFileInfo).GetConstructors();
System.Reflection.ConstructorInfo? inDirectory = typeof(UaFileInfo).GetConstructor(
[typeof(UaDirectoryInfo), typeof(NodeId), typeof(QualifiedName)]);
System.Reflection.ConstructorInfo? detached = typeof(UaFileInfo).GetConstructor(
[typeof(FileSystemClient), typeof(NodeId), typeof(QualifiedName)]);
Assert.Multiple(() =>
{
Assert.That(inDirectory, Is.Not.Null, "UaFileInfo(UaDirectoryInfo, NodeId, QualifiedName)");
Assert.That(detached, Is.Not.Null, "UaFileInfo(FileSystemClient, NodeId, QualifiedName)");
Assert.That(constructors, Has.Length.EqualTo(2));
});
}
[Test]
public async Task FileInfoCreatedInAKnownDirectoryRefreshesAndDeletesAsync()
{
var harness = FileSystemSessionHarness.Create();
var props = new FileProperties
{
Size = 4_096UL,
Writable = false,
UserWritable = false,
OpenCount = 1
};
props.Realize();
NodeId subdirId = harness.RegisterDirectory(harness.Root, new QualifiedName("subdir"));
var fileId = new NodeId(8100u);
var name = new QualifiedName("known.bin");
harness.RegisterFile(subdirId, name, fileId, props);
var client = new FileSystemClient(harness.Session, harness.Root);
UaDirectoryInfo subdir = await client.GetDirectoryAsync("/subdir").ConfigureAwait(false);
var file = new UaFileInfo(subdir, fileId, name);
await file.RefreshAsync().ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(file.Owner, Is.SameAs(client));
Assert.That(file.Parent, Is.SameAs(subdir));
Assert.That(file.IsDetached, Is.False);
Assert.That(file.NodeId, Is.EqualTo(fileId));
Assert.That(file.FullPath, Is.EqualTo("/subdir/known.bin"));
Assert.That(file.Size, Is.EqualTo(4_096UL));
Assert.That(file.OpenCount, Is.EqualTo(1));
Assert.That(file.Proxy, Is.Not.Null);
});
int callsBeforeDelete = harness.CallRequests.Count;
await file.DeleteAsync().ConfigureAwait(false);
Assert.That(harness.CallRequests, Has.Count.EqualTo(callsBeforeDelete + 1));
CallMethodRequest request = harness.CallRequests[^1];
request.MethodId.TryGetValue(out uint methodId);
request.InputArguments[0].TryGetValue(out NodeId deleted);
Assert.Multiple(() =>
{
Assert.That(methodId, Is.EqualTo(Methods.FileDirectoryType_DeleteFileSystemObject));
Assert.That(request.ObjectId, Is.EqualTo(subdirId));
Assert.That(deleted, Is.EqualTo(fileId));
});
}
[Test]
public async Task DetachedFileInfoRefreshesButRejectsDeleteMoveAndCopyAsync()
{
var harness = FileSystemSessionHarness.Create();
var props = new FileProperties
{
Size = 2_048UL,
Writable = true,
UserWritable = true,
OpenCount = 0
};
props.Realize();
var fileId = new NodeId(8101u);
var name = new QualifiedName("result.bin");
harness.RegisterFile(harness.Root, name, fileId, props);
var client = new FileSystemClient(harness.Session, harness.Root);
var file = new UaFileInfo(client, fileId, name);
await file.RefreshAsync().ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(file.Owner, Is.SameAs(client));
Assert.That(file.Parent, Is.Null);
Assert.That(file.IsDetached, Is.True);
Assert.That(file.Segments, Is.EqualTo(new[] { name }));
Assert.That(file.Size, Is.EqualTo(2_048UL));
});
int callsBeforeOperations = harness.CallRequests.Count;
int invocationsBeforeOperations = harness.SessionMock.Invocations.Count;
InvalidOperationException? delete = Assert.ThrowsAsync<InvalidOperationException>(
async () => await file.DeleteAsync().ConfigureAwait(false));
InvalidOperationException? move = Assert.ThrowsAsync<InvalidOperationException>(
async () => await file.MoveToAsync(client.Root, "moved.bin").ConfigureAwait(false));
InvalidOperationException? copy = Assert.ThrowsAsync<InvalidOperationException>(
async () => await file.CopyToAsync("/copied.bin").ConfigureAwait(false));
// A nested destination is not resolved first: the directory does
// not exist, and the detached file is still the reason given.
InvalidOperationException? nestedMove = Assert.ThrowsAsync<InvalidOperationException>(
async () => await file.MoveToAsync("/missing/moved.bin").ConfigureAwait(false));
InvalidOperationException? nestedCopy = Assert.ThrowsAsync<InvalidOperationException>(
async () => await file.CopyToAsync("/missing/copied.bin").ConfigureAwait(false));
IOException? root = Assert.ThrowsAsync<IOException>(
async () => await client.Root.DeleteAsync().ConfigureAwait(false));
Assert.Multiple(() =>
{
Assert.That(delete!.Message, Does.Contain("cannot be deleted").And.Contain("not known"));
Assert.That(move!.Message, Does.Contain("cannot be moved").And.Contain("not known"));
Assert.That(copy!.Message, Does.Contain("cannot be copied").And.Contain("not known"));
Assert.That(nestedMove!.Message, Does.Contain("cannot be moved").And.Contain("not known"));
Assert.That(nestedCopy!.Message, Does.Contain("cannot be copied").And.Contain("not known"));
Assert.That(root!.Message, Does.Contain("root directory"));
Assert.That(harness.CallRequests, Has.Count.EqualTo(callsBeforeOperations));
Assert.That(harness.SessionMock.Invocations, Has.Count.EqualTo(invocationsBeforeOperations));
});
}
[Test]
public void FileInfoConstructorsRejectMissingArguments()
{
var harness = FileSystemSessionHarness.Create();
var client = new FileSystemClient(harness.Session, harness.Root);
var name = new QualifiedName("file.bin");
Assert.Multiple(() =>
{
Assert.That(
() => new UaFileInfo((UaDirectoryInfo)null!, new NodeId(1u), name),
Throws.ArgumentNullException);
Assert.That(
() => new UaFileInfo(client.Root, NodeId.Null, name),
Throws.ArgumentNullException);
Assert.That(
() => new UaFileInfo((FileSystemClient)null!, new NodeId(1u), name),
Throws.ArgumentNullException);
Assert.That(
() => new UaFileInfo(client, NodeId.Null, name),
Throws.ArgumentNullException);
});
}
[Test]
public async Task RefreshAsyncPopulatesMandatoryPropertiesAsync()
{