Skip to content

Commit 129c697

Browse files
committed
fix stack overflow in WriteAllBytesAsync
1 parent ad61a7e commit 129c697

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

src/Directory.Build.props

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
<Project>
33
<PropertyGroup>
44
<NoWarn>CS1591;NETSDK1138;NU1901;NU1902;NU1903;CA1822;CA1847;CA1861;NU1510;NU1608;NU1109</NoWarn>
5-
<Version>9.3.0</Version>
5+
<Version>9.3.1</Version>
66
<AssemblyVersion>1.0.0</AssemblyVersion>
77
<PackageTags>Polyfill</PackageTags>
88
<DisableImplicitNamespaceImports>true</DisableImplicitNamespaceImports>

src/Polyfill/FilePolyfill.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,11 @@ public static void AppendAllBytes(string path, ReadOnlySpan<byte> bytes)
8989
/// Asynchronously creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is truncated and overwritten.
9090
/// </summary>
9191
//Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-readonlymemory((system-byte))-system-threading-cancellationtoken)
92-
public static Task WriteAllBytesAsync(string path, ReadOnlyMemory<byte> bytes, CancellationToken cancellationToken = default) =>
93-
WriteAllBytesAsync(path, bytes.ToArray(), cancellationToken);
92+
public static async Task WriteAllBytesAsync(string path, ReadOnlyMemory<byte> bytes, CancellationToken cancellationToken = default)
93+
{
94+
using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true);
95+
await stream.WriteAsync(bytes.ToArray(), 0, bytes.Length, cancellationToken);
96+
}
9497

9598
/// <summary>
9699
/// Creates a new file, writes the specified string to the file, and then closes the file.

src/Tests/FilePolyfillTests.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,17 @@ public async Task WriteAllBytesAsync()
148148
var result = await File.ReadAllBytesAsync(TestFilePath);
149149
Assert.AreEqual(data, result);
150150
}
151+
152+
[Test]
153+
public async Task WriteAllBytesAsyncMemory()
154+
{
155+
ReadOnlyMemory<byte> data = "Hello, Write Bytes!"u8.ToArray();
156+
await File.WriteAllBytesAsync(TestFilePath, data);
157+
158+
var result = await File.ReadAllTextAsync(TestFilePath);
159+
Assert.AreEqual("Hello, Write Bytes!", result);
160+
}
161+
151162
#endif
152163

153164
[Test]

0 commit comments

Comments
 (0)