Skip to content

FileObject Class

Naveen Dharmathunga edited this page Jan 19, 2026 · 1 revision

FileObject Class

Represents a file in the file system and provides methods for file manipulation, including copying, moving, deleting, renaming, and reading or writing file data to streams.

Namespace: Rheo.Storage

Assembly: Rheo.Storage.dll

Definition

public class FileObject : FileHandler, IFileObject

Inheritance

ObjectStorageObject → FileHandler → FileObject

Implements

Constructors

Constructor Description
FileObject(String) Initializes a new instance of the FileObject class for the specified file path.

Properties

Property Type Description
Information FileInformation Gets file-specific metadata including type, size, MIME type, and analysis results.
Name String Gets the name of the file without the path.
ParentDirectory String Gets the full path of the parent directory.
FullPath String Gets the full path of the file.
IsDisposed Boolean Gets a value indicating whether this file object has been disposed.

Methods

Method Description
Copy(String, Boolean) Creates a copy of the current file at the specified destination path.
Copy(String, IProgress<StorageProgress>, Boolean) Creates a copy with progress reporting.
CopyAsync(String, Boolean, CancellationToken) Asynchronously copies the file to the specified destination.
CopyAsync(String, IProgress<StorageProgress>, Boolean, CancellationToken) Asynchronously copies the file with progress reporting.
Delete() Deletes the file from the file system.
DeleteAsync(CancellationToken) Asynchronously deletes the file.
Move(String, Boolean) Moves the file to the specified destination path.
Move(String, IProgress<StorageProgress>, Boolean) Moves the file with progress reporting.
MoveAsync(String, Boolean, CancellationToken) Asynchronously moves the file to the specified destination.
MoveAsync(String, IProgress<StorageProgress>, Boolean, CancellationToken) Asynchronously moves the file with progress reporting.
Rename(String) Renames the file to the specified new name.
RenameAsync(String, CancellationToken) Asynchronously renames the file.
Write(Byte[]) Writes the specified byte array to the file.
Write(Byte[], IProgress<StorageProgress>) Writes the byte array with progress reporting.
WriteAsync(Stream, CancellationToken) Asynchronously writes stream content to the file.
WriteAsync(Stream, IProgress<StorageProgress>, CancellationToken) Asynchronously writes stream content with progress reporting.

Remarks

FileObject instances encapsulate file operations with thread safety and support both synchronous and asynchronous workflows. The class ensures that the underlying file exists upon initialization and provides mechanisms for progress reporting and cancellation in long-running operations. FileObject is designed to be used in scenarios where robust file management and integration with streams are required.

All file operations are thread-safe and use internal locking mechanisms to prevent concurrent access issues. Operations automatically handle file availability checking and will wait for locked files to become available before proceeding.

The class maintains a time-based cache for file information (valid for 1 second) to optimize repeated property access while ensuring data freshness.


Constructor Details

FileObject(String)

Initializes a new instance of the FileObject class for the specified file path.

public FileObject(string path)

Parameters

path String

The path to the file to be represented by this object. Cannot be null or empty.

Remarks

If the file does not exist at the specified path, it will be created automatically. The file is created with read/write access and shared for both reading and writing, allowing other processes to access it concurrently. The parent directory is created if it doesn't exist.

Examples

// Create or open an existing file
using var file = new FileObject(@"C:\Documents\myfile.txt");

// File is guaranteed to exist after construction
Console.WriteLine($"File exists: {File.Exists(file.FullPath)}");

Property Details

Information

Gets file-specific metadata including type, size, MIME type, and analysis results.

public FileInformation Information { get; }

Property Value

FileInformation

An object containing detailed file metadata and content analysis results.

Exceptions

InvalidOperationException

Thrown if the underlying information is not of type FileInformation.

Remarks

This property uses a time-based cache with a 1-second validity period to optimize performance. The information is automatically refreshed if the cache has expired or if file changes are detected through the Changed event.


Name

Gets the name of the file without the path.

public override string Name { get; }

Property Value

String

The file name with extension (e.g., "document.pdf").

Remarks

This property is thread-safe and always returns the current file name, even after rename or move operations.


ParentDirectory

Gets the full path of the parent directory.

public string ParentDirectory { get; }

Property Value

String

The absolute path to the parent directory.


FullPath

Gets the full path of the file.

public string FullPath { get; }

Property Value

String

The complete absolute path to the file.

Remarks

This property is automatically updated when the file is moved or renamed through the Changed event mechanism.


IsDisposed

Gets a value indicating whether this file object has been disposed.

public bool IsDisposed { get; }

Property Value

Boolean

true if the object has been disposed; otherwise, false.


Method Details

Copy(String, Boolean)

Creates a copy of the current file at the specified destination path.

public IFileObject Copy(string destination, bool overwrite)

Parameters

destination String

The full path where the file copy will be created. This must include the file name and extension.

overwrite Boolean

true to overwrite the destination file if it already exists; otherwise, false.

Returns

IFileObject

A new FileObject instance representing the copied file.

Exceptions

InvalidOperationException

Thrown if the copy operation fails due to I/O errors or insufficient permissions.

Remarks

The operation waits for the source file to become available before copying. The parent directory of the destination is created if it doesn't exist. This is a synchronous operation that blocks until the copy is complete.


Copy(String, IProgress<StorageProgress>, Boolean)

Creates a copy of the current file with progress reporting.

public IFileObject Copy(
    string destination,
    IProgress<StorageProgress>? progress,
    bool overwrite = false
)

Parameters

destination String

The full path where the file will be copied.

progress IProgress<StorageProgress>

An optional progress reporter that receives updates about bytes transferred and transfer speed. May be null.

overwrite Boolean

true to overwrite the destination file if it exists; otherwise, false. Default is false.

Returns

IFileObject

A new FileObject instance representing the copied file.

Remarks

Progress updates include total bytes, bytes transferred, and bytes per second. The buffer size is automatically calculated based on file size (1 KB to 16 MB).


CopyAsync(String, Boolean, CancellationToken)

Asynchronously copies the file to the specified destination.

public Task<IFileObject> CopyAsync(
    string destination,
    bool overwrite,
    CancellationToken cancellationToken = default
)

Parameters

destination String

The path to which the file will be copied.

overwrite Boolean

true to overwrite the destination file if it already exists; otherwise, false.

cancellationToken CancellationToken

A cancellation token that can be used to cancel the copy operation.

Returns

Task<IFileObject>

A task representing the asynchronous operation, containing the copied file object.

Remarks

The asynchronous operation uses FileOptions.Asynchronous for optimal I/O performance. The operation is thread-safe and can be canceled via the cancellation token.


CopyAsync(String, IProgress<StorageProgress>, Boolean, CancellationToken)

Asynchronously copies the file with progress reporting.

public Task<IFileObject> CopyAsync(
    string destination,
    IProgress<StorageProgress>? progress,
    bool overwrite = false,
    CancellationToken cancellationToken = default
)

Parameters

destination String

The destination path where the file will be copied.

progress IProgress<StorageProgress>

An optional progress handler that receives progress updates during the copy operation.

overwrite Boolean

true to overwrite the file at the destination if it already exists; otherwise, false.

cancellationToken CancellationToken

A cancellation token that can be used to cancel the copy operation.

Returns

Task<IFileObject>

A task representing the asynchronous copy operation, containing the copied file object.


Delete()

Deletes the file from the file system.

public void Delete()

Remarks

The operation waits for the file to become available before deletion. After deletion, a Changed event is raised with StorageChangeType.Deleted, which automatically disposes the FileObject. If the file has already been deleted, the event is still raised.


DeleteAsync(CancellationToken)

Asynchronously deletes the file.

public Task DeleteAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

A token to monitor for cancellation requests.

Returns

Task

A task representing the asynchronous delete operation.

Remarks

The deletion is performed asynchronously and honors cancellation requests. After successful deletion, the FileObject is automatically disposed.


Move(String, Boolean)

Moves the file to the specified destination path.

public void Move(string destination, bool overwrite)

Parameters

destination String

The destination path where the file will be moved.

overwrite Boolean

true to overwrite the destination if it exists; otherwise, false.

Remarks

If the source and destination are on the same volume, the move is performed as a fast directory entry update. For cross-volume moves, the file is copied to the destination and deleted from the source. A Changed event with StorageChangeType.Relocated is raised, automatically updating the FullPath property.


Move(String, IProgress<StorageProgress>, Boolean)

Moves the file with progress reporting.

public void Move(
    string destination,
    IProgress<StorageProgress>? progress,
    bool overwrite = false
)

Parameters

destination String

The destination path where the file will be moved.

progress IProgress<StorageProgress>

An optional progress reporter for move progress.

overwrite Boolean

true to overwrite the destination if it exists; otherwise, false.

Remarks

Progress reporting is primarily useful for cross-volume moves, which involve copying data. Same-volume moves report completion immediately as they only update directory entries.


MoveAsync(String, Boolean, CancellationToken)

Asynchronously moves the file to the specified destination.

public Task MoveAsync(
    string destination,
    bool overwrite,
    CancellationToken cancellationToken = default
)

Parameters

destination String

The destination path where the file will be moved.

overwrite Boolean

true to overwrite the destination if it exists; otherwise, false.

cancellationToken CancellationToken

A token to monitor for cancellation requests.

Returns

Task

A task representing the asynchronous move operation.

Remarks

For cross-volume moves, if the operation is canceled or fails after copying but before deleting the source, the copied file is automatically rolled back (deleted).


MoveAsync(String, IProgress<StorageProgress>, Boolean, CancellationToken)

Asynchronously moves the file with progress reporting.

public Task MoveAsync(
    string destination,
    IProgress<StorageProgress>? progress,
    bool overwrite = false,
    CancellationToken cancellationToken = default
)

Parameters

destination String

The destination path where the file will be moved.

progress IProgress<StorageProgress>

An optional progress reporter for move progress.

overwrite Boolean

true to overwrite the destination if it exists; otherwise, false.

cancellationToken CancellationToken

A token to monitor for cancellation requests.

Returns

Task

A task representing the asynchronous move operation.


Rename(String)

Renames the file to the specified new name.

public void Rename(string newName)

Parameters

newName String

The new name for the file. Cannot be null or empty and must be a valid file name.

Remarks

The file remains in the same directory; only the name changes. After renaming, a Changed event with StorageChangeType.Relocated is raised, updating the FullPath and Name properties automatically.


RenameAsync(String, CancellationToken)

Asynchronously renames the file.

public Task RenameAsync(string newName, CancellationToken cancellationToken = default)

Parameters

newName String

The new name to assign to the file. Cannot be null or empty.

cancellationToken CancellationToken

A cancellation token that can be used to cancel the rename operation.

Returns

Task

A task representing the asynchronous rename operation.


Write(Byte[])

Writes the specified byte array to the file.

public void Write(byte[] content)

Parameters

content Byte[]

The byte array containing the data to write. Cannot be null.

Remarks

This operation replaces the entire file content with the provided data. The file is overwritten atomically. After writing, a Changed event with StorageChangeType.Modified is raised.


Write(Byte[], IProgress<StorageProgress>)

Writes the byte array with progress reporting.

public void Write(byte[] content, IProgress<StorageProgress> progress)

Parameters

content Byte[]

The byte array containing the data to write. Cannot be null.

progress IProgress<StorageProgress>

An object that receives progress updates during the write operation.

Remarks

Progress updates include bytes transferred, total bytes, and transfer speed in bytes per second.


WriteAsync(Stream, CancellationToken)

Asynchronously writes stream content to the file.

public Task WriteAsync(Stream stream, CancellationToken cancellationToken = default)

Parameters

stream Stream

The source stream to read from. Must be readable and will be read from the current position (or beginning if seekable).

cancellationToken CancellationToken

A cancellation token that can be used to cancel the asynchronous write operation.

Returns

Task

A task representing the asynchronous write operation.

Remarks

This method is thread-safe. The stream is automatically seeked to the beginning before reading if it supports seeking. The file content is completely replaced.


WriteAsync(Stream, IProgress<StorageProgress>, CancellationToken)

Asynchronously writes stream content with progress reporting.

public Task WriteAsync(
    Stream stream,
    IProgress<StorageProgress> progress,
    CancellationToken cancellationToken = default
)

Parameters

stream Stream

The destination stream to which the object's data will be written.

progress IProgress<StorageProgress>

A progress reporter that receives updates about the write operation.

cancellationToken CancellationToken

A token that can be used to cancel the asynchronous write operation.

Returns

Task

A task representing the asynchronous write operation.

Remarks

The write operation is thread-safe. An internal semaphore ensures that concurrent operations on the same file are properly serialized.


Events

Changed

Occurs when the file changes.

public event EventHandler<StorageChangedEventArgs>? Changed

Event Type

EventHandler<StorageChangedEventArgs>

Remarks

This event is raised when the file is modified, moved, renamed, or deleted. The event provides details about the change type and updated file information. When a deletion is detected, the FileObject automatically disposes itself.


Examples

Creating and Writing to a File

using Rheo.Storage;

// Create a new file or open existing
using var file = new FileObject(@"C:\Documents\example.txt");

// Write content
byte[] data = Encoding.UTF8.GetBytes("Hello, World!");
file.Write(data);

Console.WriteLine($"File created: {file.Name}");
Console.WriteLine($"Size: {file.Information.FormattedSize}");

Copying Files with Progress

using Rheo.Storage;

using var sourceFile = new FileObject(@"C:\Videos\movie.mp4");

var progress = new Progress<StorageProgress>(p =>
{
    double percentage = (p.BytesTransferred / (double)p.TotalBytes) * 100;
    Console.WriteLine($"Copied: {percentage:F1}% ({p.BytesPerSecond / 1024 / 1024:F2} MB/s)");
});

var copiedFile = sourceFile.Copy(@"D:\Backup\movie.mp4", progress, overwrite: true);
Console.WriteLine($"Copy complete: {copiedFile.FullPath}");

Moving Files Async with Cancellation

using Rheo.Storage;

using var file = new FileObject(@"C:\Temp\document.pdf");
using var cts = new CancellationTokenSource();

var progress = new Progress<StorageProgress>(p =>
{
    Console.WriteLine($"Moving: {p.BytesTransferred} / {p.TotalBytes} bytes");
});

try
{
    // Start async move with 10-second timeout
    cts.CancelAfter(TimeSpan.FromSeconds(10));
    
    await file.MoveAsync(@"D:\Archive\document.pdf", progress, overwrite: true, cts.Token);
    Console.WriteLine("Move completed successfully.");
}
catch (OperationCanceledException)
{
    Console.WriteLine("Move operation was canceled.");
}

Monitoring File Changes

using Rheo.Storage;

using var file = new FileObject(@"C:\Documents\config.json");

file.Changed += (sender, e) =>
{
    Console.WriteLine($"Change detected: {e.ChangeType}");
    
    switch (e.ChangeType)
    {
        case StorageChangeType.Modified:
            Console.WriteLine($"New size: {e.NewInfo?.Size} bytes");
            break;
        case StorageChangeType.Relocated:
            Console.WriteLine($"New path: {e.NewInfo?.AbsolutePath}");
            break;
        case StorageChangeType.Deleted:
            Console.WriteLine("File was deleted.");
            break;
    }
};

// Perform operations
file.Write(Encoding.UTF8.GetBytes("New content"));
file.Rename("config_backup.json");
file.Delete();

Working with File Information

using Rheo.Storage;

using var file = new FileObject(@"C:\Images\photo.jpg");
var info = file.Information;

Console.WriteLine($"File: {file.Name}");
Console.WriteLine($"Type: {info.TypeName}");
Console.WriteLine($"MIME: {info.MimeType}");
Console.WriteLine($"Extension: {info.Extension}");
Console.WriteLine($"Actual Extension: {info.ActualExtension}");
Console.WriteLine($"Size: {info.FormattedSize}");
Console.WriteLine($"Created: {info.CreationTime}");
Console.WriteLine($"Modified: {info.LastWriteTime}");

Async File Operations

using Rheo.Storage;

async Task ProcessFileAsync(string sourcePath, string destPath)
{
    using var file = new FileObject(sourcePath);
    
    // Read from a stream and write to file
    using var httpClient = new HttpClient();
    using var downloadStream = await httpClient.GetStreamAsync("https://example.com/data.bin");
    
    var progress = new Progress<StorageProgress>(p =>
    {
        Console.WriteLine($"Downloaded: {p.BytesTransferred} bytes");
    });
    
    await file.WriteAsync(downloadStream, progress);
    
    // Move to final destination
    await file.MoveAsync(destPath, overwrite: true);
    
    Console.WriteLine($"File processed: {file.FullPath}");
}

Error Handling

using Rheo.Storage;

try
{
    using var file = new FileObject(@"C:\Protected\system.dat");
    file.Delete();
}
catch (UnauthorizedAccessException ex)
{
    Console.WriteLine($"Access denied: {ex.Message}");
}
catch (InvalidOperationException ex)
{
    Console.WriteLine($"Operation failed: {ex.Message}");
}

Thread Safety

FileObject is fully thread-safe. All operations use internal locking mechanisms (StateLock and Semaphore) to ensure thread-safe access. Multiple threads can safely call methods on the same instance concurrently.

Performance Considerations

  • File information is cached for 1 second to optimize repeated property access
  • Buffer sizes are automatically calculated (1 KB to 16 MB) based on file size
  • Same-volume moves are optimized as directory entry updates
  • Cross-volume moves use copy-and-delete with automatic rollback on failure
  • Async operations use FileOptions.Asynchronous for optimal I/O performance

See Also

Clone this wiki locally