Reading and writing with random access handles
With .NET 6 and later, there is a new API for working with files without needing a file stream.
First, you must get a handle to the file, as shown in the following code:
using Microsoft.Win32.SafeHandles; // SafeFileHandle
using System.Text; // Encoding
using SafeFileHandle handle =
File.OpenHandle(path: "coffee.txt",
mode: FileMode.OpenOrCreate,
access: FileAccess.ReadWrite);
You can then write some text encoded as a byte array and then stored in a read-only memory buffer to the file, as shown in the following code:
string message = "Café £4.39";
ReadOnlyMemory<byte> buffer = new(Encoding.UTF8.GetBytes(message));
await RandomAccess.WriteAsync(handle, buffer, fileOffset: 0);
To read from the file, get the length of the file, allocate a memory buffer for the contents using that length, and then read the file, as shown in the following code:
long length = RandomAccess...