OPC Studio User's Guide and Reference
OpenFile Method (IEasyUAFileTransfer)
Example 



OpcLabs.EasyOpcUA Assembly > OpcLabs.EasyOpc.UA.FileTransfer Namespace > IEasyUAFileTransfer Interface : OpenFile Method
Endpoint descriptor. Identifies the OPC-UA server.
Node descriptor of the OPC UA file.
Indicates whether the file should be opened only for read operations or for read and write operations and where the initial position is set.
Opens an OPC UA file (represented by a file object in the OPC UA address space).
Syntax
'Declaration
 
<NotNullAttribute()>
Function OpenFile( _
   ByVal endpointDescriptor As UAEndpointDescriptor, _
   ByVal fileNodeDescriptor As UANodeDescriptor, _
   ByVal openFileModes As UAOpenFileModes _
) As UAFileHandle
'Usage
 
Dim instance As IEasyUAFileTransfer
Dim endpointDescriptor As UAEndpointDescriptor
Dim fileNodeDescriptor As UANodeDescriptor
Dim openFileModes As UAOpenFileModes
Dim value As UAFileHandle
 
value = instance.OpenFile(endpointDescriptor, fileNodeDescriptor, openFileModes)

Parameters

endpointDescriptor
Endpoint descriptor. Identifies the OPC-UA server.
fileNodeDescriptor
Node descriptor of the OPC UA file.
openFileModes
Indicates whether the file should be opened only for read operations or for read and write operations and where the initial position is set.

Return Value

Returns a handle for the file used in other method calls indicating the access request and thus the position in the file. The UAFileHandle is generated by the server and is unique for the session.
Exceptions
ExceptionDescription

A null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.

This is a usage error, i.e. it will never occur (the exception will not be thrown) in a correctly written program. Your code should not catch this exception.

The OPC UA operation has failed. This operation exception in uniformly used to allow common handling of various kinds of errors. The System.Exception.InnerException always contains information about the actual error cause.

This is an operation error that depends on factors external to your program, and thus cannot be always avoided. Your code must handle it appropriately.

Remarks

This method corresponds to (but is not fully identical with) the OPC UA File Transfer Method .

The fileNodeDescriptor must be an existing node in the server, of object type OpcLabs.EasyOpc.UA.AddressSpace.Standard.UAObjectTypeIds.FileType.

When a client opens a file, it gets a file handle that is valid while the session is open. Clients cannot transfer the UAFileHandle to another session but need to get a new UAFileHandle by calling the OpenFile method. You should use the CloseFile method to release the handle when they do not need access to the file anymore. Make sure you also explicitly call System.IDisposable.Dispose on the file handle returned from OpenFile. The OPC UA file handle, until disposed of, causes the client to keep a session open on the server.

"Clients can open the same file several times for read. A request to open for writing shall return Bad_NotWritable when the file is already opened. A request to open for reading shall return Bad_NotReadable when the file is already opened for writing."

This method will throw an exception if the file you are attempting to open does not exist.

Recommendation: Whenever possible, do not use this method directly, and use a higher-level abstraction instead. You can create System.IO.Stream objects for accessing the file data by using methods like OpcLabs.EasyOpc.UA.IO.Extensions.IEasyUAFileTransferExtension2.OpenOrCreateStream, or obtain them through a file provider (using IEasyUAFileTransferExtension.GetFileProvider2 or IEasyUAFileTransferExtension.GetWritableFileProvider).

Example

.NET

.NET

// Shows how to read different sections from an OPC UA file, using the file transfer client.
// Note: Consider using a higher-level abstraction, OPC UA file provider, instead.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

using System;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.FileTransfer;
using OpcLabs.EasyOpc.UA.OperationModel;

namespace UADocExamples.FileTransfer._EasyUAFileTransferClient
{
    class ReadAndSetFilePosition
    {
        public static void Main1()
        {
            // Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            UAEndpointDescriptor endpointDescriptor = "opc.tcp://localhost:48030";

            // A node that represents an instance of OPC UA FileType object.
            UANodeDescriptor fileNodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile";
            
            // Instantiate the file transfer client object
            var fileTransferClient = new EasyUAFileTransferClient();

            // Open the file, read two separate sections of it, and close it.
            try
            {
                Console.WriteLine("Opening file...");
                using (UAFileHandle fileHandle = fileTransferClient.OpenFile(endpointDescriptor, fileNodeDescriptor, UAOpenFileModes.Read))
                {
                    Console.WriteLine("Reading first file section...");
                    byte[] bytes1 = fileTransferClient.ReadFile(endpointDescriptor, fileNodeDescriptor, fileHandle, length:16);
                    Console.WriteLine($"First section: {BitConverter.ToString(bytes1)}");

                    Console.WriteLine("Reading second file section...");
                    byte[] bytes2 = fileTransferClient.ReadFile(endpointDescriptor, fileNodeDescriptor, fileHandle, length: 10);
                    Console.WriteLine($"Second section: {BitConverter.ToString(bytes2)}");

                    Console.WriteLine("Setting file position...");
                    fileTransferClient.SetFilePosition(endpointDescriptor, fileNodeDescriptor, fileHandle, position:100);

                    Console.WriteLine("Reading third file section...");
                    byte[] bytes3 = fileTransferClient.ReadFile(endpointDescriptor, fileNodeDescriptor, fileHandle, length: 20);
                    Console.WriteLine($"Third section: {BitConverter.ToString(bytes3)}");

                    Console.WriteLine("Closing file...");
                    fileTransferClient.CloseFile(endpointDescriptor, fileNodeDescriptor, fileHandle);
                }
            }
            catch (UAException uaException)
            {
                Console.WriteLine("*** Failure: {0}", uaException.GetBaseException().Message);
                return;
            }

            Console.WriteLine("Finished...");
        }
    }
}
# Shows how to read different sections from an OPC UA file, using the file transfer client.
# Note: Consider using a higher-level abstraction, OPC UA file provider, instead.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc

# Import .NET namespaces.
from System import *
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.FileTransfer import *
from OpcLabs.EasyOpc.UA.OperationModel import *


# Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe).
endpointDescriptor = UAEndpointDescriptor('opc.tcp://localhost:48030')

# A node that represents an instance of OPC UA FileType object.
fileNodeDescriptor = UANodeDescriptor('nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile')

# Instantiate the file transfer client object.
fileTransferClient = EasyUAFileTransferClient()

# Open the file, read two separate sections of it, and close it.
fileHandle = None
try:
    print('Opening file...')
    fileHandle = fileTransferClient.OpenFile(endpointDescriptor, fileNodeDescriptor, UAOpenFileModes.Read)

    print('Reading first file section...')
    bytes1 = fileTransferClient.ReadFile(endpointDescriptor, fileNodeDescriptor, fileHandle, 16)    # length
    print('First section: ', BitConverter.ToString(bytes1), sep='')

    print('Reading second file section...')
    bytes2 = fileTransferClient.ReadFile(endpointDescriptor, fileNodeDescriptor, fileHandle, 10)    # length
    print('Second section: ', BitConverter.ToString(bytes2), sep='')

    print('Setting file position...')
    fileTransferClient.SetFilePosition(endpointDescriptor, fileNodeDescriptor, fileHandle, 100) # position

    print('Reading third file section...')
    bytes3 = fileTransferClient.ReadFile(endpointDescriptor, fileNodeDescriptor, fileHandle, 20)    # length
    print('Third section: ', BitConverter.ToString(bytes3), sep='')

    print('Closing file...')
    fileTransferClient.CloseFile(endpointDescriptor, fileNodeDescriptor, fileHandle)

except UAException as uaException:
    print('*** Failure: ' + uaException.GetBaseException().Message)
    exit()

finally:
    fileHandle and fileHandle.Dispose()

print()
print('Finished.')
' Shows how to read different sections from an OPC UA file, using the file transfer client.
' Note: Consider using a higher-level abstraction, OPC UA file provider, instead.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

Imports OpcLabs.EasyOpc.UA
Imports OpcLabs.EasyOpc.UA.FileTransfer
Imports OpcLabs.EasyOpc.UA.OperationModel

Namespace FileTransfer._EasyUAFileTransferClient

    Friend Class ReadAndSetFilePosition

        Public Shared Sub Main1()

            ' Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            Dim endpointDescriptor As UAEndpointDescriptor = "opc.tcp://localhost:48030"

            ' A node that represents an instance of OPC UA FileType object.
            Dim fileNodeDescriptor As UANodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile"

            ' Instantiate the file transfer client object
            Dim fileTransferClient = New EasyUAFileTransferClient

            ' Open the file, read two separate sections of it, and close it.
            Try
                Console.WriteLine("Opening file...")
                Using fileHandle As UAFileHandle = fileTransferClient.OpenFile(endpointDescriptor, fileNodeDescriptor, UAOpenFileModes.Read)
                    Console.WriteLine("Reading first file section...")
                    Dim bytes1 As Byte() = fileTransferClient.ReadFile(endpointDescriptor, fileNodeDescriptor, fileHandle, 16)
                    Console.WriteLine($"First section: {BitConverter.ToString(bytes1)}")

                    Console.WriteLine("Reading second file section...")
                    Dim bytes2 As Byte() = fileTransferClient.ReadFile(endpointDescriptor, fileNodeDescriptor, fileHandle, 10)
                    Console.WriteLine($"Second section: {BitConverter.ToString(bytes2)}")

                    Console.WriteLine("Setting file position...")
                    fileTransferClient.SetFilePosition(endpointDescriptor, fileNodeDescriptor, fileHandle, 100)

                    Console.WriteLine("Reading third file section...")
                    Dim bytes3 As Byte() = fileTransferClient.ReadFile(endpointDescriptor, fileNodeDescriptor, fileHandle, 20)
                    Console.WriteLine($"Third section: {BitConverter.ToString(bytes3)}")

                    Console.WriteLine("Closing file...")
                    fileTransferClient.CloseFile(endpointDescriptor, fileNodeDescriptor, fileHandle)
                End Using
            Catch uaException As UAException
                Console.WriteLine("*** Failure: {0}", uaException.GetBaseException.Message)
                Exit Sub
            End Try

            Console.WriteLine("Finished...")
        End Sub
    End Class
End Namespace
// Shows how to write data into a section of an OPC UA file, using the file transfer client.
// Note: Consider using a higher-level abstraction, OPC UA file provider, instead.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

using System;
using System.Text;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.FileTransfer;
using OpcLabs.EasyOpc.UA.OperationModel;

namespace UADocExamples.FileTransfer._EasyUAFileTransferClient
{
    class WriteFile
    {
        public static void Main1()
        {
            // Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            UAEndpointDescriptor endpointDescriptor = "opc.tcp://localhost:48030";

            // A node that represents an instance of OPC UA FileType object.
            UANodeDescriptor fileNodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile";
            
            // Instantiate the file transfer client object
            var fileTransferClient = new EasyUAFileTransferClient();

            // Open the file, write a section of it, and close it.
            try
            {
                Console.WriteLine("Opening file...");
                using (UAFileHandle fileHandle = fileTransferClient.OpenFile(endpointDescriptor, fileNodeDescriptor, 
                    UAOpenFileModes.Read | UAOpenFileModes.Write))
                {
                    Console.WriteLine("Writing file section...");
                    byte[] data = Encoding.UTF8.GetBytes("TEXT FROM FILE TRANSFER CLIENT EXAMPLE. Demonstrates writing a section of a file. <<<");
                    fileTransferClient.WriteFile(endpointDescriptor, fileNodeDescriptor, fileHandle, data);

                    Console.WriteLine("Closing file...");
                    fileTransferClient.CloseFile(endpointDescriptor, fileNodeDescriptor, fileHandle);
                }
            }
            catch (UAException uaException)
            {
                Console.WriteLine("*** Failure: {0}", uaException.GetBaseException().Message);
                return;
            }

            Console.WriteLine();
            Console.WriteLine("Finished...");
        }
    }
}
# Shows how to write data into a section of an OPC UA file, using the file transfer client.
# Note: Consider using a higher-level abstraction, OPC UA file provider, instead.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc

# Import .NET namespaces.
from System import *
from System.Text import *
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.Extensions import *
from OpcLabs.EasyOpc.UA.FileTransfer import *
from OpcLabs.EasyOpc.UA.OperationModel import *


# Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe).
endpointDescriptor = UAEndpointDescriptor('opc.tcp://localhost:48030')
endpointDescriptor = UAEndpointDescriptorExtension.WithUserNameIdentity(endpointDescriptor,'john', 'master')

# A node that represents an instance of OPC UA FileType object.
fileNodeDescriptor = UANodeDescriptor('nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile')

# Instantiate the file transfer client object.
fileTransferClient = EasyUAFileTransferClient()

# Prevent prompt to trust the server certificate (INSECURE, used just for smooth example flow).
EasyUAClient.SharedParameters.EngineParameters.CertificateAcceptancePolicy.TrustEndpointUrlString(
    endpointDescriptor.UrlString)

# Open the file, write a section of it, and close it.
fileHandle = None
try:
    print('Opening file...')
    fileHandle = fileTransferClient.OpenFile(endpointDescriptor, fileNodeDescriptor,
                                             UAOpenFileModes.Read | UAOpenFileModes.Write)

    print('Writing file section...')
    data = Encoding.UTF8.GetBytes('TEXT FROM FILE TRANSFER CLIENT EXAMPLE. Demonstrates writing a section of a file. '
                                  '<<<')
    fileTransferClient.WriteFile(endpointDescriptor, fileNodeDescriptor, fileHandle, data)

    print('Closing file...')
    fileTransferClient.CloseFile(endpointDescriptor, fileNodeDescriptor, fileHandle)

except UAException as uaException:
    print('*** Failure: ' + uaException.GetBaseException().Message)
    exit()

finally:
    fileHandle and fileHandle.Dispose()

print()
print('Finished.')
' Shows how to write data into a section of an OPC UA file, using the file transfer client.
' Note: Consider using a higher-level abstraction, OPC UA file provider, instead.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

Imports System.Text
Imports OpcLabs.EasyOpc.UA
Imports OpcLabs.EasyOpc.UA.FileTransfer
Imports OpcLabs.EasyOpc.UA.OperationModel

Namespace FileTransfer._EasyUAFileTransferClient

    Friend Class WriteFile

        Public Shared Sub Main1()

            ' Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            Dim endpointDescriptor As UAEndpointDescriptor = "opc.tcp://localhost:48030"

            ' A node that represents an instance of OPC UA FileType object.
            Dim fileNodeDescriptor As UANodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile"

            ' Instantiate the file transfer client object
            Dim fileTransferClient = New EasyUAFileTransferClient

            ' Open the file, write a section of it, and close it.
            Try
                Console.WriteLine("Opening file...")
                Using fileHandle As UAFileHandle = fileTransferClient.OpenFile(endpointDescriptor, fileNodeDescriptor,
                    UAOpenFileModes.Read Or UAOpenFileModes.Write)
                    Console.WriteLine("Writing file section...")
                    Dim data As Byte() = Encoding.UTF8.GetBytes("TEXT FROM FILE TRANSFER CLIENT EXAMPLE. Demonstrates writing a section of a file. <<<")
                    fileTransferClient.WriteFile(endpointDescriptor, fileNodeDescriptor, fileHandle, data)

                    Console.WriteLine("Closing file...")
                    fileTransferClient.CloseFile(endpointDescriptor, fileNodeDescriptor, fileHandle)
                End Using
            Catch uaException As UAException
                Console.WriteLine("*** Failure: {0}", uaException.GetBaseException.Message)
                Exit Sub
            End Try

            Console.WriteLine()
            Console.WriteLine("Finished...")
        End Sub
    End Class
End Namespace
Requirements

Target Platforms: .NET Framework: Windows 10 (selected versions), Windows 11 (selected versions), Windows Server 2016, Windows Server 2022; .NET: Linux, macOS, Microsoft Windows

See Also