From de6d95e9dc1f1e601dc9072f52dd18e9aa04ee8d Mon Sep 17 00:00:00 2001 From: rameel Date: Sat, 21 Mar 2026 23:29:41 +0500 Subject: [PATCH] Fix and simplify WriteAllTextAsync implementation - Fix incorrect use of GetMaxCharCount instead of GetMaxByteCount - Fix behavior for zero-length content --- .../VirtualFileExtensions.cs | 35 ++----------------- 1 file changed, 3 insertions(+), 32 deletions(-) diff --git a/src/Ramstack.FileSystem.Abstractions/VirtualFileExtensions.cs b/src/Ramstack.FileSystem.Abstractions/VirtualFileExtensions.cs index ba52bf5..91c86cc 100644 --- a/src/Ramstack.FileSystem.Abstractions/VirtualFileExtensions.cs +++ b/src/Ramstack.FileSystem.Abstractions/VirtualFileExtensions.cs @@ -263,7 +263,7 @@ static void Error_EndOfStream() => /// A representing the asynchronous operation. /// public static ValueTask WriteAllTextAsync(this VirtualFile file, string contents, CancellationToken cancellationToken = default) => - WriteAllTextAsync(file, contents.AsMemory(), Utf8NoBom, cancellationToken); + WriteAllTextAsync(file, contents.AsMemory(), encoding: null, cancellationToken); /// /// Asynchronously writes the specified string to the current file. If the file already exists, it is truncated and overwritten. @@ -302,38 +302,9 @@ public static ValueTask WriteAllTextAsync(this VirtualFile file, ReadOnlyMemory< /// public static async ValueTask WriteAllTextAsync(this VirtualFile file, ReadOnlyMemory contents, Encoding? encoding, CancellationToken cancellationToken = default) { - const int ChunkSize = 8192; - - if (contents.IsEmpty) - return; - - encoding ??= Utf8NoBom; var stream = await file.OpenWriteAsync(cancellationToken).ConfigureAwait(false); - - var preamble = encoding.GetPreamble(); - if (preamble.Length != 0) - stream.Write(preamble.AsSpan()); - - var bytes = ArrayPool.Shared.Rent( - encoding.GetMaxCharCount(Math.Min(ChunkSize, contents.Length))); - - try - { - var encoder = encoding.GetEncoder(); - while (contents.Length != 0) - { - var data = contents[..Math.Min(ChunkSize, contents.Length)]; - contents = contents[data.Length..]; - - var encoded = encoder.GetBytes(data.Span, bytes.AsSpan(), flush: contents.IsEmpty); - await stream.WriteAsync(bytes.AsMemory(0, encoded), cancellationToken).ConfigureAwait(false); - } - } - finally - { - await stream.DisposeAsync().ConfigureAwait(false); - ArrayPool.Shared.Return(bytes); - } + await using var writer = new StreamWriter(stream, encoding!); + await writer.WriteAsync(contents, cancellationToken).ConfigureAwait(false); } ///