File
Namespace: Wisej.Ext.ClientFileSystem
Assembly: Wisej.Ext.ClientFileSystem (4.1.0.0)
Represents a File of a ClientFileSystem.
- C#
- VB.NET
public class File : IDisposable
Public Class File
Inherits IDisposable
An instance is a handle on a file the user chose in the browser, not a path on the server. Handles come from ShowOpenFilePickerAsync, ShowSaveFilePickerAsync and GetFilesAsync; application code never constructs one directly.
Name, Size, Type and LastModified are captured when the handle is created and are not refreshed afterwards, so they describe the file as it was at that moment.
Each instance pins an object in the browser's registry and implements IDisposable. Dispose it when it is no longer needed rather than waiting for the finalizer, which runs at a time the application does not control.
Example:
var files = await ClientFileSystem.ShowOpenFilePickerAsync(false, false, "Text files|text/plain|.txt");
using (var file = files[0])
{
AlertBox.Show($"{file.Name}, {file.Size} bytes, last modified {file.LastModified:d}.");
var text = await file.ReadTextAsync();
AlertBox.Show(text);
}
Constructors
File(config)
Creates a new instance of File from the handle description returned by the browser.
| Name | Type | Description |
|---|---|---|
| config | Object | The dynamic configuration object sent by the client, carrying the handle's hash, name, size, type and last-modified date. |
This constructor exists for the extension itself. Application code obtains a File from a picker or from GetFilesAsync instead of calling it.
Throws:
- ArgumentNullException
config is
null.
Properties
LastModified
DateTime: Returns the file's last modification date.
Value: A DateTime holding the modification date reported by the browser when this handle was created. It is a snapshot: writing through this instance does not update it.
Name
String: Returns the file's name.
Value: A String containing the file name, without any path information. The browser never exposes the full path of a file to the application.
Size
Int32: Returns the file size.
Value: The length of the file in bytes when this handle was created. It is a snapshot: writing through this instance does not update it. Useful as the starting position for an append.
Type
String: Returns the file type.
Value: The MIME type the browser inferred for the file, such as text/plain. Empty when the browser cannot determine a type from the file's extension.
Methods
CallAsync(name, args)
Asynchronously runs the JavaScript within the component's context in the browser and returns an awaitable Task containing the value returned by the remote call.
| Parameter | Type | Description |
|---|---|---|
| name | String | Represents the function name. |
| args | Object[] | The arguments to pass to the function. |
Returns: Task<Object>. An awaitable Task that represents the asynchronous operation.
Dispose()
Releases the client-side handle that this File represents.
The handle is an entry in the browser's object registry, not an unmanaged resource: this method sends a single fire-and-forget request to release it and does not wait for confirmation. Disposing does not delete the file from the user's disk.
The instance is not guarded after disposal: the properties keep returning their cached values, and further calls are sent with a handle the browser no longer recognizes, failing with "Invalid file system handle". No ObjectDisposedException is raised.
An undisposed File releases its handle from the finalizer instead, which runs at a time the application does not control and may not run at all before the session ends. A session that enumerates folders repeatedly will accumulate handles in the browser until then, so dispose each one as soon as it is no longer needed.
Example:
var files = await directory.GetFilesAsync("*.txt");
foreach (var file in files)
{
AlertBox.Show(file.Name);
file.Dispose();
}
Finalize()
Destroys an instance of File.
QueryPermission(mode, callback)
Queries the current state of the specified permission on the File, without prompting the user.
| Parameter | Type | Description |
|---|---|---|
| mode | Permission | One of the Permission values: Read to read the file, ReadWrite to also modify it. |
| callback | Action<PermissionState> | A method invoked on the application context with one of the PermissionState values. A failed call reports Denied, which is indistinguishable here from a real refusal; use the asynchronous overload to tell the two apart. |
Treat Prompt as "not yet granted" rather than as a refusal: the browser has not decided and will ask when the file is next accessed.
Throws:
- ArgumentNullException
callback is
null.
Example:
file.QueryPermission(Permission.ReadWrite, state =>
{
if (state != PermissionState.Granted)
AlertBox.Show($"Write access is {state}.");
});
QueryPermissionAsync(mode)
Queries the current state of the specified permission on the File asynchronously, without prompting the user.
| Parameter | Type | Description |
|---|---|---|
| mode | Permission | One of the Permission values: Read to read the file, ReadWrite to also modify it. |
Returns: Task<PermissionState>. An awaitable Task that completes with one of the PermissionState values.
Treat Prompt as "not yet granted" rather than as a refusal: the browser has not decided and will ask when the file is next accessed.
Throws:
- NotSupportedException The browser returned a permission state that is not one of the recognized values.
Example:
var state = await file.QueryPermissionAsync(Permission.ReadWrite);
if (state != PermissionState.Granted)
state = await file.RequestPermissionAsync(Permission.ReadWrite);
ReadBytes(callback)
Reads the whole content of the File as raw bytes.
| Parameter | Type | Description |
|---|---|---|
| callback | Action<Byte[]> | A method invoked on the application context with the file's contents. A failed read reports an empty array rather than null, so an empty result does not by itself mean the file is empty. |
This method returns immediately. The whole file is buffered in memory on the way through, so prefer it for files small enough to hold comfortably.
Throws:
- ArgumentNullException
callback is
null.
Example:
file.ReadBytes(bytes =>
{
AlertBox.Show($"{bytes.Length} bytes read from {file.Name}.");
});
ReadBytesAsync()
Reads the whole content of the File as raw bytes, asynchronously.
Returns: Task<Byte[]>. An awaitable Task that completes with the file's contents.
Unlike ReadTextAsync, this method swallows a failed read and returns an empty array instead of faulting, so an empty result does not distinguish an empty file from a file that could not be read. Check Size when that distinction matters. The whole file is buffered in memory on the way through.
Example:
var bytes = await file.ReadBytesAsync();
if (bytes.Length == 0 && file.Size > 0)
AlertBox.Show($"{file.Name} could not be read.");
else
AlertBox.Show($"{bytes.Length} bytes read.");
ReadText(callback)
Opens a text file, reads all the text in the file into a string, and then closes the file.
| Parameter | Type | Description |
|---|---|---|
| callback | Action<String> | A method invoked on the application context with the file's contents, or with null if the read failed. |
This method returns immediately. The content is decoded as UTF-8.
Throws:
- ArgumentNullException
callback is
null.
Example:
file.ReadText(text =>
{
if (text == null)
{
AlertBox.Show("The file could not be read.");
return;
}
AlertBox.Show($"{text.Length} characters read.");
});
ReadTextAsync()
Opens a text file, reads all the text in the file into a string, and then closes the file asynchronously.
Returns: Task<String>. An awaitable Task that completes with all the text in the file, decoded as UTF-8.
The task faults if the file can no longer be read: the handle was disposed, the user revoked permission, or the file was removed since it was picked.
Example:
try
{
var text = await file.ReadTextAsync();
AlertBox.Show($"{file.Name} contains {text.Length} characters.");
}
catch (Exception ex)
{
AlertBox.Show($"Could not read {file.Name}: {ex.Message}");
}
RequestPermission(mode, callback)
Requests the specified permission on the File, prompting the user if the browser has not already decided.
| Parameter | Type | Description |
|---|---|---|
| mode | Permission | One of the Permission values: Read to read the file, ReadWrite to also modify it. |
| callback | Action<PermissionState> | A method invoked on the application context with one of the PermissionState values. A failed call reports Denied, which is indistinguishable here from a real refusal; use the asynchronous overload to tell the two apart. |
The browser shows its prompt only in response to a user gesture, so call this from a control event rather than during application startup. Requesting a permission that has already been granted returns Granted without prompting again. Treat Prompt as "not yet granted" rather than as a refusal.
Throws:
- ArgumentNullException
callback is
null.
Example:
file.RequestPermission(Permission.ReadWrite, state =>
{
if (state == PermissionState.Granted)
file.WriteText("Saved.", 0, success => { });
else
AlertBox.Show($"Write access is {state}.");
});
RequestPermissionAsync(mode)
Requests the specified permission on the File asynchronously, prompting the user if the browser has not already decided.
| Parameter | Type | Description |
|---|---|---|
| mode | Permission | One of the Permission values: Read to read the file, ReadWrite to also modify it. |
Returns: Task<PermissionState>. An awaitable Task that completes with one of the PermissionState values.
The browser shows its prompt only in response to a user gesture, so call this from a control event rather than during application startup. Requesting a permission that has already been granted returns Granted without prompting again. Treat Prompt as "not yet granted" rather than as a refusal.
Throws:
- NotSupportedException The browser returned a permission state that is not one of the recognized values.
Example:
var state = await file.RequestPermissionAsync(Permission.ReadWrite);
if (state != PermissionState.Granted)
{
AlertBox.Show($"Cannot write to {file.Name}: permission is {state}.");
return;
}
await file.WriteTextAsync("Saved.", 0);
Truncate(size, callback)
Resizes the file associated with stream to be size bytes long. If size is larger than the current file size this pads the file with null bytes, otherwise it truncates the file.
| Parameter | Type | Description |
|---|---|---|
| size | Int32 | The new length of the stream. |
| callback | Action<Boolean> | A method invoked on the application context with true if the operation completed, or false if it failed. The callback carries no indication of the cause; the asynchronous overload surfaces the underlying exception. |
The file cursor is updated when truncate is called. If the offset is smaller than offset, it remains unchanged.
If the offset is larger than size, the offset is set to size to ensure that subsequent writes do not error.
No changes are written to the actual file on disk until the stream has been closed. Changes are typically written to a temporary file instead.
Resizing requires that ReadWrite has been granted; request it with RequestPermissionAsync first.
Throws:
- ArgumentNullException
callback is
null.
Example:
// Empty the file before rewriting it.
file.Truncate(0, success =>
{
if (success)
file.WriteText("Fresh contents.", 0, written => { });
});
TruncateAsync(size)
Resizes the file associated with stream to be size bytes long. If size is larger than the current file size this pads the file with null bytes, otherwise it truncates the file.
| Parameter | Type | Description |
|---|---|---|
| size | Int32 | The new length of the stream. |
Returns: Task. An awaitable Task that represents the asynchronous operation.
The file cursor is updated when truncate is called. If the offset is smaller than offset, it remains unchanged.
If the offset is larger than size, the offset is set to size to ensure that subsequent writes do not error.
No changes are written to the actual file on disk until the stream has been closed. Changes are typically written to a temporary file instead.
Resizing requires that ReadWrite has been granted; request it with RequestPermissionAsync first.
Example:
// Replace the file outright: empty it, then write from the beginning.
await file.TruncateAsync(0);
await file.WriteTextAsync("Fresh contents.", 0);
WriteBytes(bytes, type, keepExistingData, position, callback)
Writes an array of Byte starting from a position in the file.
| Parameter | Type | Description |
|---|---|---|
| bytes | Byte[] | The Byte array to write. |
| type | WritableType | One of the WritableType values describing the action to perform. Write is the usual choice. |
| keepExistingData | Boolean | true to copy the current contents into the stream before writing, so bytes outside the written range survive; false to start from an empty file, discarding everything not written by this call. |
| position | Int32 | The byte offset in the file at which the write starts. Pass 0 to write from the beginning, or Size to append. |
| callback | Action<Boolean> | A method invoked on the application context with true if the operation completed, or false if it failed. The callback carries no indication of the cause; the asynchronous overload surfaces the underlying exception. |
This method returns immediately. Writing requires that ReadWrite has been granted; request it with RequestPermissionAsync first. Note that this overload takes its arguments in a different order from WriteBytesAsync.
Throws:
- ArgumentNullException
callback is
null.
Example:
var bytes = System.Text.Encoding.UTF8.GetBytes("binary payload");
file.WriteBytes(bytes, WritableType.Write, false, 0, success =>
{
AlertBox.Show(success ? "Saved." : "The file could not be written.");
});
WriteBytesAsync(bytes, position, type, keepExistingData)
Writes an array of Byte starting from a position in the file, asynchronously.
| Parameter | Type | Description |
|---|---|---|
| bytes | Byte[] | The Byte array to write. |
| position | Int32 | The byte offset in the file at which the write starts. Pass 0 to write from the beginning, or Size to append. |
| type | WritableType | One of the WritableType values describing the action to perform. Write is the usual choice. |
| keepExistingData | Boolean | true to copy the current contents into the stream before writing, so bytes outside the written range survive; false to start from an empty file, discarding everything not written by this call. |
Returns: Task. An awaitable Task that represents the asynchronous operation.
Writing requires that ReadWrite has been granted; request it with RequestPermissionAsync first. Note that this overload takes its arguments in a different order from WriteBytes.
Example:
var bytes = await BuildImageAsync();
await file.WriteBytesAsync(bytes, 0, WritableType.Write, false);
AlertBox.Show($"Wrote {bytes.Length} bytes to {file.Name}.");
WriteText(text, position, callback)
Writes text into the file starting at the specified position.
| Parameter | Type | Description |
|---|---|---|
| text | String | The text to write, encoded as UTF-8. |
| position | Int32 | The byte offset in the file at which the write starts. Pass 0 to write from the beginning, or Size to append. |
| callback | Action<Boolean> | A method invoked on the application context with true if the operation completed, or false if it failed. The callback carries no indication of the cause; the asynchronous overload surfaces the underlying exception. |
Writing requires that ReadWrite has been granted on the file or on the directory it came from; request it with RequestPermissionAsync first. The underlying stream is opened with the existing content preserved, so a write shorter than the current file replaces only the bytes it covers and leaves the remainder in place. Call TruncateAsync first when the file should be replaced outright. Size is not updated by a write; re-enumerate the folder to observe the new length.
Throws:
- ArgumentNullException
callback is
null.
Example:
// Append a line to the end of the file.
file.WriteText($"Logged at {DateTime.Now}.\r\n", file.Size, success =>
{
AlertBox.Show(success ? "Saved." : "The file could not be written.");
});
WriteTextAsync(text, position)
Writes text into the file starting at the specified position, asynchronously.
| Parameter | Type | Description |
|---|---|---|
| text | String | The text to write, encoded as UTF-8. |
| position | Int32 | The byte offset in the file at which the write starts. Pass 0 to write from the beginning, or Size to append. |
Returns: Task. An awaitable Task that represents the asynchronous operation.
Writing requires that ReadWrite has been granted on the file or on the directory it came from; request it with RequestPermissionAsync first. The underlying stream is opened with the existing content preserved, so a write shorter than the current file replaces only the bytes it covers and leaves the remainder in place. Call TruncateAsync first when the file should be replaced outright. Size is not updated by a write; re-enumerate the folder to observe the new length.
Example:
var state = await file.RequestPermissionAsync(Permission.ReadWrite);
if (state == PermissionState.Granted)
{
await file.TruncateAsync(0);
await file.WriteTextAsync("Replaced contents.", 0);
}