-
Notifications
You must be signed in to change notification settings - Fork 0
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
public class FileObject : FileHandler, IFileObjectObject → StorageObject → FileHandler → FileObject
| Constructor | Description |
|---|---|
| FileObject(String) | Initializes a new instance of the FileObject class for the specified file path. |
| 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. |
| 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. |
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.
Initializes a new instance of the FileObject class for the specified file path.
public FileObject(string path)path String
The path to the file to be represented by this object. Cannot be null or empty.
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.
// 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)}");Gets file-specific metadata including type, size, MIME type, and analysis results.
public FileInformation Information { get; }An object containing detailed file metadata and content analysis results.
Thrown if the underlying information is not of type FileInformation.
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.
Gets the name of the file without the path.
public override string Name { get; }The file name with extension (e.g., "document.pdf").
This property is thread-safe and always returns the current file name, even after rename or move operations.
Gets the full path of the parent directory.
public string ParentDirectory { get; }The absolute path to the parent directory.
Gets the full path of the file.
public string FullPath { get; }The complete absolute path to the file.
This property is automatically updated when the file is moved or renamed through the Changed event mechanism.
Gets a value indicating whether this file object has been disposed.
public bool IsDisposed { get; }true if the object has been disposed; otherwise, false.
Creates a copy of the current file at the specified destination path.
public IFileObject Copy(string destination, bool overwrite)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.
A new FileObject instance representing the copied file.
Thrown if the copy operation fails due to I/O errors or insufficient permissions.
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.
Creates a copy of the current file with progress reporting.
public IFileObject Copy(
string destination,
IProgress<StorageProgress>? progress,
bool overwrite = false
)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.
A new FileObject instance representing the copied file.
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).
Asynchronously copies the file to the specified destination.
public Task<IFileObject> CopyAsync(
string destination,
bool overwrite,
CancellationToken cancellationToken = default
)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.
A task representing the asynchronous operation, containing the copied file object.
The asynchronous operation uses FileOptions.Asynchronous for optimal I/O performance. The operation is thread-safe and can be canceled via the cancellation token.
Asynchronously copies the file with progress reporting.
public Task<IFileObject> CopyAsync(
string destination,
IProgress<StorageProgress>? progress,
bool overwrite = false,
CancellationToken cancellationToken = default
)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.
A task representing the asynchronous copy operation, containing the copied file object.
Deletes the file from the file system.
public void Delete()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.
Asynchronously deletes the file.
public Task DeleteAsync(CancellationToken cancellationToken = default)cancellationToken CancellationToken
A token to monitor for cancellation requests.
A task representing the asynchronous delete operation.
The deletion is performed asynchronously and honors cancellation requests. After successful deletion, the FileObject is automatically disposed.
Moves the file to the specified destination path.
public void Move(string destination, bool overwrite)destination String
The destination path where the file will be moved.
overwrite Boolean
true to overwrite the destination if it exists; otherwise, false.
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.
Moves the file with progress reporting.
public void Move(
string destination,
IProgress<StorageProgress>? progress,
bool overwrite = false
)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.
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.
Asynchronously moves the file to the specified destination.
public Task MoveAsync(
string destination,
bool overwrite,
CancellationToken cancellationToken = default
)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.
A task representing the asynchronous move operation.
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).
Asynchronously moves the file with progress reporting.
public Task MoveAsync(
string destination,
IProgress<StorageProgress>? progress,
bool overwrite = false,
CancellationToken cancellationToken = default
)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.
A task representing the asynchronous move operation.
Renames the file to the specified new name.
public void Rename(string newName)newName String
The new name for the file. Cannot be null or empty and must be a valid file name.
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.
Asynchronously renames the file.
public Task RenameAsync(string newName, CancellationToken cancellationToken = default)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.
A task representing the asynchronous rename operation.
Writes the specified byte array to the file.
public void Write(byte[] content)content Byte[]
The byte array containing the data to write. Cannot be null.
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.
Writes the byte array with progress reporting.
public void Write(byte[] content, IProgress<StorageProgress> progress)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.
Progress updates include bytes transferred, total bytes, and transfer speed in bytes per second.
Asynchronously writes stream content to the file.
public Task WriteAsync(Stream stream, CancellationToken cancellationToken = default)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.
A task representing the asynchronous write operation.
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.
Asynchronously writes stream content with progress reporting.
public Task WriteAsync(
Stream stream,
IProgress<StorageProgress> progress,
CancellationToken cancellationToken = default
)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.
A task representing the asynchronous write operation.
The write operation is thread-safe. An internal semaphore ensures that concurrent operations on the same file are properly serialized.
Occurs when the file changes.
public event EventHandler<StorageChangedEventArgs>? ChangedEventHandler<StorageChangedEventArgs>
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.
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}");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}");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.");
}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();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}");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}");
}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}");
}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.
- 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
-
Storage Objects
-
Storage Information
-
Platform-Specific
-
Content-Type Analysis
-
Results
-
Models
-
-
Events & Progress