Skip to content

Commit

Permalink
Simplify File.WriteAllTextAsync (#55644)
Browse files Browse the repository at this point in the history
Avoid the unnecessary ArrayPool usage and extra layer of buffering.
  • Loading branch information
stephentoub authored Jul 15, 2021
1 parent d3a8a19 commit 9717cf5
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/libraries/System.Private.CoreLib/src/System/IO/File.cs
Original file line number Diff line number Diff line change
Expand Up @@ -921,6 +921,7 @@ private static async Task InternalWriteAllLinesAsync(TextWriter writer, IEnumera

private static async Task InternalWriteAllTextAsync(StreamWriter sw, string contents, CancellationToken cancellationToken)
{
#if MS_IO_REDIST
char[]? buffer = null;
try
{
Expand All @@ -931,11 +932,7 @@ private static async Task InternalWriteAllTextAsync(StreamWriter sw, string cont
{
int batchSize = Math.Min(DefaultBufferSize, count - index);
contents.CopyTo(index, buffer, 0, batchSize);
#if MS_IO_REDIST
await sw.WriteAsync(buffer, 0, batchSize).ConfigureAwait(false);
#else
await sw.WriteAsync(new ReadOnlyMemory<char>(buffer, 0, batchSize), cancellationToken).ConfigureAwait(false);
#endif
index += batchSize;
}

Expand All @@ -950,6 +947,13 @@ private static async Task InternalWriteAllTextAsync(StreamWriter sw, string cont
ArrayPool<char>.Shared.Return(buffer);
}
}
#else
using (sw)
{
await sw.WriteAsync(contents.AsMemory(), cancellationToken).ConfigureAwait(false);
await sw.FlushAsync().ConfigureAwait(false);
}
#endif
}

public static Task AppendAllTextAsync(string path, string? contents, CancellationToken cancellationToken = default(CancellationToken))
Expand Down

0 comments on commit 9717cf5

Please sign in to comment.