From 6699c85a98ca61b3bf764e54e58ab53ca4d258b3 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 12 Oct 2026 21:35:33 +1100 Subject: [PATCH 1/2] Read lines until ReadLineAsync returns null in the File polyfills --- src/Polyfill/FilePolyfill.cs | 22 +- src/Split/net461/FilePolyfill.cs | 18 +- src/Split/net462/FilePolyfill.cs | 18 +- src/Split/net47/FilePolyfill.cs | 18 +- src/Split/net471/FilePolyfill.cs | 18 +- src/Split/net472/FilePolyfill.cs | 18 +- src/Split/net48/FilePolyfill.cs | 18 +- src/Split/net481/FilePolyfill.cs | 18 +- src/Split/net5.0/FilePolyfill.cs | 9 +- src/Split/net6.0/FilePolyfill.cs | 9 +- src/Split/netcoreapp2.0/FilePolyfill.cs | 9 +- src/Split/netcoreapp2.1/FilePolyfill.cs | 9 +- src/Split/netcoreapp2.2/FilePolyfill.cs | 9 +- src/Split/netcoreapp3.0/FilePolyfill.cs | 9 +- src/Split/netcoreapp3.1/FilePolyfill.cs | 9 +- src/Split/netstandard2.0/FilePolyfill.cs | 18 +- src/Split/netstandard2.1/FilePolyfill.cs | 9 +- src/Split/uap10.0/FilePolyfill.cs | 18 +- src/Tests/FilePolyfillTests.cs | 261 +++++++++++++++++++++++ 19 files changed, 349 insertions(+), 168 deletions(-) diff --git a/src/Polyfill/FilePolyfill.cs b/src/Polyfill/FilePolyfill.cs index 6b262dae..3f687bac 100644 --- a/src/Polyfill/FilePolyfill.cs +++ b/src/Polyfill/FilePolyfill.cs @@ -310,14 +310,13 @@ public static async Task ReadAllLinesAsync(string path, Encoding encod var lines = new List(); using var reader = AsyncStreamReader(path, encoding); - while (!reader.EndOfStream) + // Reading until ReadLineAsync returns null, rather than testing EndOfStream before each + // line, keeps every read asynchronous: EndOfStream refills an empty buffer with a blocking read. + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - lines.Add(line); - } + lines.Add(line); } return lines.ToArray(); @@ -363,14 +362,13 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + // Reading until ReadLineAsync returns null, rather than testing EndOfStream before each + // line, keeps every read asynchronous: EndOfStream refills an empty buffer with a blocking read. + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } diff --git a/src/Split/net461/FilePolyfill.cs b/src/Split/net461/FilePolyfill.cs index 449002b8..46f2fbc3 100644 --- a/src/Split/net461/FilePolyfill.cs +++ b/src/Split/net461/FilePolyfill.cs @@ -231,14 +231,11 @@ public static async Task ReadAllLinesAsync(string path, Encoding encod { var lines = new List(); using var reader = AsyncStreamReader(path, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - lines.Add(line); - } + lines.Add(line); } return lines.ToArray(); } @@ -273,14 +270,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/net462/FilePolyfill.cs b/src/Split/net462/FilePolyfill.cs index 449002b8..46f2fbc3 100644 --- a/src/Split/net462/FilePolyfill.cs +++ b/src/Split/net462/FilePolyfill.cs @@ -231,14 +231,11 @@ public static async Task ReadAllLinesAsync(string path, Encoding encod { var lines = new List(); using var reader = AsyncStreamReader(path, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - lines.Add(line); - } + lines.Add(line); } return lines.ToArray(); } @@ -273,14 +270,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/net47/FilePolyfill.cs b/src/Split/net47/FilePolyfill.cs index 449002b8..46f2fbc3 100644 --- a/src/Split/net47/FilePolyfill.cs +++ b/src/Split/net47/FilePolyfill.cs @@ -231,14 +231,11 @@ public static async Task ReadAllLinesAsync(string path, Encoding encod { var lines = new List(); using var reader = AsyncStreamReader(path, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - lines.Add(line); - } + lines.Add(line); } return lines.ToArray(); } @@ -273,14 +270,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/net471/FilePolyfill.cs b/src/Split/net471/FilePolyfill.cs index 449002b8..46f2fbc3 100644 --- a/src/Split/net471/FilePolyfill.cs +++ b/src/Split/net471/FilePolyfill.cs @@ -231,14 +231,11 @@ public static async Task ReadAllLinesAsync(string path, Encoding encod { var lines = new List(); using var reader = AsyncStreamReader(path, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - lines.Add(line); - } + lines.Add(line); } return lines.ToArray(); } @@ -273,14 +270,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/net472/FilePolyfill.cs b/src/Split/net472/FilePolyfill.cs index 449002b8..46f2fbc3 100644 --- a/src/Split/net472/FilePolyfill.cs +++ b/src/Split/net472/FilePolyfill.cs @@ -231,14 +231,11 @@ public static async Task ReadAllLinesAsync(string path, Encoding encod { var lines = new List(); using var reader = AsyncStreamReader(path, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - lines.Add(line); - } + lines.Add(line); } return lines.ToArray(); } @@ -273,14 +270,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/net48/FilePolyfill.cs b/src/Split/net48/FilePolyfill.cs index 449002b8..46f2fbc3 100644 --- a/src/Split/net48/FilePolyfill.cs +++ b/src/Split/net48/FilePolyfill.cs @@ -231,14 +231,11 @@ public static async Task ReadAllLinesAsync(string path, Encoding encod { var lines = new List(); using var reader = AsyncStreamReader(path, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - lines.Add(line); - } + lines.Add(line); } return lines.ToArray(); } @@ -273,14 +270,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/net481/FilePolyfill.cs b/src/Split/net481/FilePolyfill.cs index 449002b8..46f2fbc3 100644 --- a/src/Split/net481/FilePolyfill.cs +++ b/src/Split/net481/FilePolyfill.cs @@ -231,14 +231,11 @@ public static async Task ReadAllLinesAsync(string path, Encoding encod { var lines = new List(); using var reader = AsyncStreamReader(path, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - lines.Add(line); - } + lines.Add(line); } return lines.ToArray(); } @@ -273,14 +270,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/net5.0/FilePolyfill.cs b/src/Split/net5.0/FilePolyfill.cs index 8a78fe59..b2707dcc 100644 --- a/src/Split/net5.0/FilePolyfill.cs +++ b/src/Split/net5.0/FilePolyfill.cs @@ -120,14 +120,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/net6.0/FilePolyfill.cs b/src/Split/net6.0/FilePolyfill.cs index 2bf69cb6..f76534d0 100644 --- a/src/Split/net6.0/FilePolyfill.cs +++ b/src/Split/net6.0/FilePolyfill.cs @@ -120,14 +120,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/netcoreapp2.0/FilePolyfill.cs b/src/Split/netcoreapp2.0/FilePolyfill.cs index d3868fbe..b4d570a1 100644 --- a/src/Split/netcoreapp2.0/FilePolyfill.cs +++ b/src/Split/netcoreapp2.0/FilePolyfill.cs @@ -127,14 +127,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/netcoreapp2.1/FilePolyfill.cs b/src/Split/netcoreapp2.1/FilePolyfill.cs index d3868fbe..b4d570a1 100644 --- a/src/Split/netcoreapp2.1/FilePolyfill.cs +++ b/src/Split/netcoreapp2.1/FilePolyfill.cs @@ -127,14 +127,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/netcoreapp2.2/FilePolyfill.cs b/src/Split/netcoreapp2.2/FilePolyfill.cs index d3868fbe..b4d570a1 100644 --- a/src/Split/netcoreapp2.2/FilePolyfill.cs +++ b/src/Split/netcoreapp2.2/FilePolyfill.cs @@ -127,14 +127,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/netcoreapp3.0/FilePolyfill.cs b/src/Split/netcoreapp3.0/FilePolyfill.cs index 8a78fe59..b2707dcc 100644 --- a/src/Split/netcoreapp3.0/FilePolyfill.cs +++ b/src/Split/netcoreapp3.0/FilePolyfill.cs @@ -120,14 +120,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/netcoreapp3.1/FilePolyfill.cs b/src/Split/netcoreapp3.1/FilePolyfill.cs index 8a78fe59..b2707dcc 100644 --- a/src/Split/netcoreapp3.1/FilePolyfill.cs +++ b/src/Split/netcoreapp3.1/FilePolyfill.cs @@ -120,14 +120,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/netstandard2.0/FilePolyfill.cs b/src/Split/netstandard2.0/FilePolyfill.cs index c1f1ee23..c7489f21 100644 --- a/src/Split/netstandard2.0/FilePolyfill.cs +++ b/src/Split/netstandard2.0/FilePolyfill.cs @@ -235,14 +235,11 @@ public static async Task ReadAllLinesAsync(string path, Encoding encod { var lines = new List(); using var reader = AsyncStreamReader(path, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - lines.Add(line); - } + lines.Add(line); } return lines.ToArray(); } @@ -277,14 +274,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/netstandard2.1/FilePolyfill.cs b/src/Split/netstandard2.1/FilePolyfill.cs index d3868fbe..b4d570a1 100644 --- a/src/Split/netstandard2.1/FilePolyfill.cs +++ b/src/Split/netstandard2.1/FilePolyfill.cs @@ -127,14 +127,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Split/uap10.0/FilePolyfill.cs b/src/Split/uap10.0/FilePolyfill.cs index c1f1ee23..c7489f21 100644 --- a/src/Split/uap10.0/FilePolyfill.cs +++ b/src/Split/uap10.0/FilePolyfill.cs @@ -235,14 +235,11 @@ public static async Task ReadAllLinesAsync(string path, Encoding encod { var lines = new List(); using var reader = AsyncStreamReader(path, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - lines.Add(line); - } + lines.Add(line); } return lines.ToArray(); } @@ -277,14 +274,11 @@ public static async IAsyncEnumerable ReadLinesAsync(string path, Encodin { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line != null) - { - yield return line; - } + yield return line; } } #endif diff --git a/src/Tests/FilePolyfillTests.cs b/src/Tests/FilePolyfillTests.cs index ecc74b7b..3e28cad3 100644 --- a/src/Tests/FilePolyfillTests.cs +++ b/src/Tests/FilePolyfillTests.cs @@ -744,4 +744,265 @@ public async Task FileInfo_CreateAsHardLink_ThrowsIfTargetNotFound() await Assert.That(() => fileInfo.CreateAsHardLink("nonexistent.txt")).Throws(); } + + static string CreateReadLinesTestDirectory() + { + var directory = Path.Combine(Path.GetTempPath(), "PolyfillFileReadLines_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + return directory; + } + + // File contents chosen around the reader's buffer sizes (1024 and 4096 bytes), so that lines end + // exactly on, just before and just after a buffer boundary, and line terminators get split by one. + static IEnumerable ReadLinesContents() + { + yield return ""; + yield return "\n"; + yield return "\r\n"; + yield return "\r"; + yield return "\n\n\n"; + yield return "single line without terminator"; + yield return "one\ntwo\r\nthree\rfour"; + yield return "one\ntwo\r\nthree\rfour\n"; + yield return "trailing blank lines\n\n\n"; + yield return "\n\nleading blank lines"; + yield return "a\u00e9\u4f60\U0001F30D\nb\u00e9\u4f60\U0001F30D\r\n"; + + foreach (var boundary in new[] {1024, 2048, 4096, 8192}) + { + foreach (var delta in new[] {-2, -1, 0, 1, 2}) + { + foreach (var terminator in new[] {"\n", "\r\n", "\r", ""}) + { + // the first line ends boundary + delta bytes into the file + var length = boundary + delta - terminator.Length; + yield return new string('x', length) + terminator; + yield return new string('x', length) + terminator + "next"; + yield return new string('x', length) + terminator + "next\n"; + } + } + } + + // many lines of the same length, so that buffer boundaries land on every position of a line + var builder = new StringBuilder(); + for (var index = 0; index < 5000; index++) + { + builder.Append("line ").Append(index % 10).Append("\r\n"); + } + + yield return builder.ToString(); + + // lines that are each exactly one buffer long + builder.Clear(); + for (var index = 0; index < 20; index++) + { + builder.Append('y', 1023).Append('\n'); + } + + yield return builder.ToString(); + + // one line much longer than any buffer + yield return new string('z', 100_000); + yield return new string('z', 100_000) + "\n" + new string('w', 50_000); + } + + [Test] + public async Task ReadAllLinesAsync_MatchesReadAllLines() + { + var directory = CreateReadLinesTestDirectory(); + try + { + var path = Path.Combine(directory, "lines.txt"); + var index = 0; + foreach (var content in ReadLinesContents()) + { + index++; + File.WriteAllText(path, content, new UTF8Encoding(false)); + var expected = File.ReadAllLines(path); + + var actual = await File.ReadAllLinesAsync(path); + + if (!actual.SequenceEqual(expected)) + { + throw new($"ReadAllLinesAsync differs from ReadAllLines for content {index} ({content.Length} chars): {actual.Length} lines rather than {expected.Length}"); + } + } + } + finally + { + Directory.Delete(directory, true); + } + } + + [Test] + public async Task ReadAllLinesAsync_Encodings_MatchReadAllLines() + { + var directory = CreateReadLinesTestDirectory(); + try + { + var path = Path.Combine(directory, "lines.txt"); + var builder = new StringBuilder(); + for (var index = 0; index < 3000; index++) + { + builder.Append("a\u00e9\u4f60\U0001F30D ").Append(index).Append(index % 2 == 0 ? "\n" : "\r\n"); + } + + var content = builder.ToString(); + var encodings = new Encoding[] + { + new UTF8Encoding(false), + new UTF8Encoding(true), + new UnicodeEncoding(false, true), + new UnicodeEncoding(true, true), + new UTF32Encoding(false, true) + }; + foreach (var encoding in encodings) + { + File.WriteAllText(path, content, encoding); + var expected = File.ReadAllLines(path, encoding); + + await Assert.That((await File.ReadAllLinesAsync(path, encoding)).SequenceEqual(expected)).IsTrue(); + + // a byte order mark overrides the encoding that was asked for + if (encoding.GetPreamble().Length > 0) + { + await Assert.That((await File.ReadAllLinesAsync(path)).SequenceEqual(expected)).IsTrue(); + await Assert.That((await File.ReadAllLinesAsync(path, Encoding.ASCII)).SequenceEqual(expected)).IsTrue(); + } + } + } + finally + { + Directory.Delete(directory, true); + } + } + + [Test] + public async Task ReadAllLinesAsync_CanceledToken_ThrowsAndReleasesFile() + { + var directory = CreateReadLinesTestDirectory(); + try + { + var path = Path.Combine(directory, "lines.txt"); + File.WriteAllText(path, "one\ntwo\n"); + using var cancelSource = new CancelSource(); + cancelSource.Cancel(); + + await Assert.That(async () => await File.ReadAllLinesAsync(path, cancelSource.Token)) + .Throws(); + + // the file is not left open + File.Delete(path); + await Assert.That(File.Exists(path)).IsFalse(); + } + finally + { + Directory.Delete(directory, true); + } + } + +#if FeatureAsyncInterfaces + [Test] + public async Task ReadLinesAsync_MatchesReadAllLines() + { + var directory = CreateReadLinesTestDirectory(); + try + { + var path = Path.Combine(directory, "lines.txt"); + var index = 0; + foreach (var content in ReadLinesContents()) + { + index++; + File.WriteAllText(path, content, new UTF8Encoding(false)); + var expected = File.ReadAllLines(path); + + var actual = new List(); + await foreach (var line in File.ReadLinesAsync(path)) + { + actual.Add(line); + } + + if (!actual.SequenceEqual(expected)) + { + throw new($"ReadLinesAsync differs from ReadAllLines for content {index} ({content.Length} chars): {actual.Count} lines rather than {expected.Length}"); + } + } + } + finally + { + Directory.Delete(directory, true); + } + } + + [Test] + public async Task ReadLinesAsync_CanceledWhileEnumerating_ThrowsAndReleasesFile() + { + var directory = CreateReadLinesTestDirectory(); + try + { + var path = Path.Combine(directory, "lines.txt"); + File.WriteAllLines(path, Enumerable.Range(0, 5000).Select(_ => "line " + _)); + using var source = new CancelSource(); + var read = new List(); + + await Assert.That(async () => + { + await foreach (var line in File.ReadLinesAsync(path, source.Token)) + { + read.Add(line); + if (read.Count == 10) + { + source.Cancel(); + } + } + }) + .Throws(); + + // The BCL only notices the cancellation at its next read from the file, so it may hand + // out a few more lines that it had already buffered. Either way the lines that were + // returned are the first ones, in order, and the enumeration stops well short of the end. + await Assert.That(read.Count >= 10).IsTrue(); + await Assert.That(read.Count < 1000).IsTrue(); + await Assert.That(read.SequenceEqual(Enumerable.Range(0, read.Count).Select(_ => "line " + _))).IsTrue(); + + // the file is not left open + File.Delete(path); + await Assert.That(File.Exists(path)).IsFalse(); + } + finally + { + Directory.Delete(directory, true); + } + } + + [Test] + public async Task ReadLinesAsync_StoppingEarly_ReleasesFile() + { + var directory = CreateReadLinesTestDirectory(); + try + { + var path = Path.Combine(directory, "lines.txt"); + File.WriteAllLines(path, Enumerable.Range(0, 5000).Select(_ => "line " + _)); + var read = new List(); + + await foreach (var line in File.ReadLinesAsync(path)) + { + read.Add(line); + if (read.Count == 3) + { + break; + } + } + + await Assert.That(read.SequenceEqual(new[] {"line 0", "line 1", "line 2"})).IsTrue(); + + File.Delete(path); + await Assert.That(File.Exists(path)).IsFalse(); + } + finally + { + Directory.Delete(directory, true); + } + } +#endif } \ No newline at end of file From 2a4b2ea7e5c983fa9b79b654dd1788e8baec97d1 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 12 Oct 2026 21:39:37 +1100 Subject: [PATCH 2/2] Move the new read tests next to the existing ones --- src/Tests/FilePolyfillTests.cs | 748 ++++++++++++++++----------------- 1 file changed, 374 insertions(+), 374 deletions(-) diff --git a/src/Tests/FilePolyfillTests.cs b/src/Tests/FilePolyfillTests.cs index 3e28cad3..06c4cddf 100644 --- a/src/Tests/FilePolyfillTests.cs +++ b/src/Tests/FilePolyfillTests.cs @@ -94,78 +94,87 @@ await Assert.That(async () => await File.ReadAllLinesAsync(nonExistent)).Throws(); } - [Test] - public async Task ReadAllLinesAsync_ThrowsIfCancelled() + static string CreateReadLinesTestDirectory() { - File.WriteAllText(restFilePath, "abc"); - var cancelSource = new CancelSource(); - cancelSource.Cancel(); - Exception? exception = null; - try + var directory = Path.Combine(Path.GetTempPath(), "PolyfillFileReadLines_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + return directory; + } + + // File contents chosen around the reader's buffer sizes (1024 and 4096 bytes), so that lines end + // exactly on, just before and just after a buffer boundary, and line terminators get split by one. + static IEnumerable ReadLinesContents() + { + yield return ""; + yield return "\n"; + yield return "\r\n"; + yield return "\r"; + yield return "\n\n\n"; + yield return "single line without terminator"; + yield return "one\ntwo\r\nthree\rfour"; + yield return "one\ntwo\r\nthree\rfour\n"; + yield return "trailing blank lines\n\n\n"; + yield return "\n\nleading blank lines"; + yield return "a\u00e9\u4f60\U0001F30D\nb\u00e9\u4f60\U0001F30D\r\n"; + + foreach (var boundary in new[] {1024, 2048, 4096, 8192}) { - await File.ReadAllLinesAsync(restFilePath, cancelSource.Token); + foreach (var delta in new[] {-2, -1, 0, 1, 2}) + { + foreach (var terminator in new[] {"\n", "\r\n", "\r", ""}) + { + // the first line ends boundary + delta bytes into the file + var length = boundary + delta - terminator.Length; + yield return new string('x', length) + terminator; + yield return new string('x', length) + terminator + "next"; + yield return new string('x', length) + terminator + "next\n"; + } + } } - catch (Exception e) + + // many lines of the same length, so that buffer boundaries land on every position of a line + var builder = new StringBuilder(); + for (var index = 0; index < 5000; index++) { - exception = e; + builder.Append("line ").Append(index % 10).Append("\r\n"); } - await Assert.That(exception).IsNotNull(); - await Assert.That(exception is OperationCanceledException or TaskCanceledException).IsTrue(); + yield return builder.ToString(); + + // lines that are each exactly one buffer long + builder.Clear(); + for (var index = 0; index < 20; index++) + { + builder.Append('y', 1023).Append('\n'); + } + + yield return builder.ToString(); + + // one line much longer than any buffer + yield return new string('z', 100_000); + yield return new string('z', 100_000) + "\n" + new string('w', 50_000); } [Test] - public async Task WriteAndAppendAsync_CancelledToken_LeavesFileUntouched() + public async Task ReadAllLinesAsync_MatchesReadAllLines() { - var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(directory); + var directory = CreateReadLinesTestDirectory(); try { - var cancelSource = new CancelSource(); - cancelSource.Cancel(); - var token = cancelSource.Token; - var bytes = Encoding.UTF8.GetBytes("new"); - var lines = new[] {"new"}; - var operations = new Dictionary> + var path = Path.Combine(directory, "lines.txt"); + var index = 0; + foreach (var content in ReadLinesContents()) { - ["WriteAllBytesAsync"] = path => File.WriteAllBytesAsync(path, bytes, token), - ["WriteAllLinesAsync"] = path => File.WriteAllLinesAsync(path, lines, token), - ["WriteAllLinesAsyncEncoding"] = path => File.WriteAllLinesAsync(path, lines, Encoding.UTF8, token), - ["WriteAllTextAsync"] = path => File.WriteAllTextAsync(path, "new", token), - ["WriteAllTextAsyncEncoding"] = path => File.WriteAllTextAsync(path, "new", Encoding.UTF8, token), - ["AppendAllBytesAsync"] = path => File.AppendAllBytesAsync(path, bytes, token), - ["AppendAllLinesAsync"] = path => File.AppendAllLinesAsync(path, lines, token), - ["AppendAllTextAsync"] = path => File.AppendAllTextAsync(path, "new", token), -#if FeatureMemory - ["WriteAllBytesAsyncMemory"] = path => File.WriteAllBytesAsync(path, new ReadOnlyMemory(bytes), token), - ["AppendAllBytesAsyncMemory"] = path => File.AppendAllBytesAsync(path, new ReadOnlyMemory(bytes), token), -#endif - }; + index++; + File.WriteAllText(path, content, new UTF8Encoding(false)); + var expected = File.ReadAllLines(path); - foreach (var operation in operations) - { - var existing = Path.Combine(directory, operation.Key + ".existing.txt"); - var missing = Path.Combine(directory, operation.Key + ".missing.txt"); - File.WriteAllText(existing, "original"); + var actual = await File.ReadAllLinesAsync(path); - foreach (var path in new[] {existing, missing}) + if (!actual.SequenceEqual(expected)) { - Exception? exception = null; - try - { - await operation.Value(path); - } - catch (Exception e) - { - exception = e; - } - - await Assert.That(exception is OperationCanceledException).IsTrue(); + throw new($"ReadAllLinesAsync differs from ReadAllLines for content {index} ({content.Length} chars): {actual.Length} lines rather than {expected.Length}"); } - - // an already cancelled token must not create or truncate the file - await Assert.That(File.ReadAllText(existing)).IsEqualTo("original"); - await Assert.That(File.Exists(missing)).IsFalse(); } } finally @@ -175,75 +184,98 @@ public async Task WriteAndAppendAsync_CancelledToken_LeavesFileUntouched() } [Test] - public async Task AppendAllTextAsync() - { - var content = "Hello, Async Text!"; - await File.AppendAllTextAsync(restFilePath, content, Encoding.UTF8); - - var result = await File.ReadAllTextAsync(restFilePath); - await Assert.That(result).IsEqualTo(content); - } - - [UnsupportedOSPlatform("windows")] - [Test] - public async Task GetUnixFileModeTest() + public async Task ReadAllLinesAsync_Encodings_MatchReadAllLines() { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + var directory = CreateReadLinesTestDirectory(); + try { - return; - } - - var expected = UnixFileMode.OtherRead | UnixFileMode.GroupRead | UnixFileMode.UserWrite | UnixFileMode.UserRead; + var path = Path.Combine(directory, "lines.txt"); + var builder = new StringBuilder(); + for (var index = 0; index < 3000; index++) + { + builder.Append("a\u00e9\u4f60\U0001F30D ").Append(index).Append(index % 2 == 0 ? "\n" : "\r\n"); + } - var sourceContent = "Test content"; - File.WriteAllText(restFilePath, sourceContent); + var content = builder.ToString(); + var encodings = new Encoding[] + { + new UTF8Encoding(false), + new UTF8Encoding(true), + new UnicodeEncoding(false, true), + new UnicodeEncoding(true, true), + new UTF32Encoding(false, true) + }; + foreach (var encoding in encodings) + { + File.WriteAllText(path, content, encoding); + var expected = File.ReadAllLines(path, encoding); - var result = File.GetUnixFileMode(restFilePath); + await Assert.That((await File.ReadAllLinesAsync(path, encoding)).SequenceEqual(expected)).IsTrue(); - await Assert.That(result).IsEqualTo(expected); + // a byte order mark overrides the encoding that was asked for + if (encoding.GetPreamble().Length > 0) + { + await Assert.That((await File.ReadAllLinesAsync(path)).SequenceEqual(expected)).IsTrue(); + await Assert.That((await File.ReadAllLinesAsync(path, Encoding.ASCII)).SequenceEqual(expected)).IsTrue(); + } + } + } + finally + { + Directory.Delete(directory, true); + } } - [UnsupportedOSPlatform("windows")] [Test] - public async Task SetUnixFileModeTest() + public async Task ReadAllLinesAsync_CanceledToken_ThrowsAndReleasesFile() { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + var directory = CreateReadLinesTestDirectory(); + try { - return; - } - - var sourceContent = "Test content"; - File.WriteAllText(restFilePath, sourceContent); - - var expected = UnixFileMode.UserWrite | UnixFileMode.UserRead; - - File.SetUnixFileMode(restFilePath, expected); + var path = Path.Combine(directory, "lines.txt"); + File.WriteAllText(path, "one\ntwo\n"); + using var cancelSource = new CancelSource(); + cancelSource.Cancel(); - var result = File.GetUnixFileMode(restFilePath); + await Assert.That(async () => await File.ReadAllLinesAsync(path, cancelSource.Token)) + .Throws(); - await Assert.That(result).IsEqualTo(expected); + // the file is not left open + File.Delete(path); + await Assert.That(File.Exists(path)).IsFalse(); + } + finally + { + Directory.Delete(directory, true); + } } - [UnsupportedOSPlatform("windows")] +#if FeatureAsyncInterfaces [Test] - public async Task GetSetUnixFileMode_PathWithSpaces() + public async Task ReadLinesAsync_MatchesReadAllLines() { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return; - } - - var directory = Path.Combine(Path.GetTempPath(), "polyfill mode " + Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(directory); - var path = Path.Combine(directory, "it's a \"file\".txt"); + var directory = CreateReadLinesTestDirectory(); try { - File.WriteAllText(path, "content"); - var expected = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead; + var path = Path.Combine(directory, "lines.txt"); + var index = 0; + foreach (var content in ReadLinesContents()) + { + index++; + File.WriteAllText(path, content, new UTF8Encoding(false)); + var expected = File.ReadAllLines(path); - File.SetUnixFileMode(path, expected); + var actual = new List(); + await foreach (var line in File.ReadLinesAsync(path)) + { + actual.Add(line); + } - await Assert.That(File.GetUnixFileMode(path)).IsEqualTo(expected); + if (!actual.SequenceEqual(expected)) + { + throw new($"ReadLinesAsync differs from ReadAllLines for content {index} ({content.Length} chars): {actual.Count} lines rather than {expected.Length}"); + } + } } finally { @@ -251,19 +283,248 @@ public async Task GetSetUnixFileMode_PathWithSpaces() } } - [UnsupportedOSPlatform("windows")] [Test] - public async Task GetSetUnixFileMode_MissingFile_Throws() + public async Task ReadLinesAsync_CanceledWhileEnumerating_ThrowsAndReleasesFile() { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + var directory = CreateReadLinesTestDirectory(); + try { - return; - } - - var missing = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"), "missing.txt"); + var path = Path.Combine(directory, "lines.txt"); + File.WriteAllLines(path, Enumerable.Range(0, 5000).Select(_ => "line " + _)); + using var source = new CancelSource(); + var read = new List(); - await Assert.That(() => File.GetUnixFileMode(missing)).Throws(); - await Assert.That(() => File.SetUnixFileMode(missing, UnixFileMode.UserRead)).Throws(); + await Assert.That(async () => + { + await foreach (var line in File.ReadLinesAsync(path, source.Token)) + { + read.Add(line); + if (read.Count == 10) + { + source.Cancel(); + } + } + }) + .Throws(); + + // The BCL only notices the cancellation at its next read from the file, so it may hand + // out a few more lines that it had already buffered. Either way the lines that were + // returned are the first ones, in order, and the enumeration stops well short of the end. + await Assert.That(read.Count >= 10).IsTrue(); + await Assert.That(read.Count < 1000).IsTrue(); + await Assert.That(read.SequenceEqual(Enumerable.Range(0, read.Count).Select(_ => "line " + _))).IsTrue(); + + // the file is not left open + File.Delete(path); + await Assert.That(File.Exists(path)).IsFalse(); + } + finally + { + Directory.Delete(directory, true); + } + } + + [Test] + public async Task ReadLinesAsync_StoppingEarly_ReleasesFile() + { + var directory = CreateReadLinesTestDirectory(); + try + { + var path = Path.Combine(directory, "lines.txt"); + File.WriteAllLines(path, Enumerable.Range(0, 5000).Select(_ => "line " + _)); + var read = new List(); + + await foreach (var line in File.ReadLinesAsync(path)) + { + read.Add(line); + if (read.Count == 3) + { + break; + } + } + + await Assert.That(read.SequenceEqual(new[] {"line 0", "line 1", "line 2"})).IsTrue(); + + File.Delete(path); + await Assert.That(File.Exists(path)).IsFalse(); + } + finally + { + Directory.Delete(directory, true); + } + } +#endif + + [Test] + public async Task ReadAllLinesAsync_ThrowsIfCancelled() + { + File.WriteAllText(restFilePath, "abc"); + var cancelSource = new CancelSource(); + cancelSource.Cancel(); + Exception? exception = null; + try + { + await File.ReadAllLinesAsync(restFilePath, cancelSource.Token); + } + catch (Exception e) + { + exception = e; + } + + await Assert.That(exception).IsNotNull(); + await Assert.That(exception is OperationCanceledException or TaskCanceledException).IsTrue(); + } + + [Test] + public async Task WriteAndAppendAsync_CancelledToken_LeavesFileUntouched() + { + var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + var cancelSource = new CancelSource(); + cancelSource.Cancel(); + var token = cancelSource.Token; + var bytes = Encoding.UTF8.GetBytes("new"); + var lines = new[] {"new"}; + var operations = new Dictionary> + { + ["WriteAllBytesAsync"] = path => File.WriteAllBytesAsync(path, bytes, token), + ["WriteAllLinesAsync"] = path => File.WriteAllLinesAsync(path, lines, token), + ["WriteAllLinesAsyncEncoding"] = path => File.WriteAllLinesAsync(path, lines, Encoding.UTF8, token), + ["WriteAllTextAsync"] = path => File.WriteAllTextAsync(path, "new", token), + ["WriteAllTextAsyncEncoding"] = path => File.WriteAllTextAsync(path, "new", Encoding.UTF8, token), + ["AppendAllBytesAsync"] = path => File.AppendAllBytesAsync(path, bytes, token), + ["AppendAllLinesAsync"] = path => File.AppendAllLinesAsync(path, lines, token), + ["AppendAllTextAsync"] = path => File.AppendAllTextAsync(path, "new", token), +#if FeatureMemory + ["WriteAllBytesAsyncMemory"] = path => File.WriteAllBytesAsync(path, new ReadOnlyMemory(bytes), token), + ["AppendAllBytesAsyncMemory"] = path => File.AppendAllBytesAsync(path, new ReadOnlyMemory(bytes), token), +#endif + }; + + foreach (var operation in operations) + { + var existing = Path.Combine(directory, operation.Key + ".existing.txt"); + var missing = Path.Combine(directory, operation.Key + ".missing.txt"); + File.WriteAllText(existing, "original"); + + foreach (var path in new[] {existing, missing}) + { + Exception? exception = null; + try + { + await operation.Value(path); + } + catch (Exception e) + { + exception = e; + } + + await Assert.That(exception is OperationCanceledException).IsTrue(); + } + + // an already cancelled token must not create or truncate the file + await Assert.That(File.ReadAllText(existing)).IsEqualTo("original"); + await Assert.That(File.Exists(missing)).IsFalse(); + } + } + finally + { + Directory.Delete(directory, true); + } + } + + [Test] + public async Task AppendAllTextAsync() + { + var content = "Hello, Async Text!"; + await File.AppendAllTextAsync(restFilePath, content, Encoding.UTF8); + + var result = await File.ReadAllTextAsync(restFilePath); + await Assert.That(result).IsEqualTo(content); + } + + [UnsupportedOSPlatform("windows")] + [Test] + public async Task GetUnixFileModeTest() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return; + } + + var expected = UnixFileMode.OtherRead | UnixFileMode.GroupRead | UnixFileMode.UserWrite | UnixFileMode.UserRead; + + var sourceContent = "Test content"; + File.WriteAllText(restFilePath, sourceContent); + + var result = File.GetUnixFileMode(restFilePath); + + await Assert.That(result).IsEqualTo(expected); + } + + [UnsupportedOSPlatform("windows")] + [Test] + public async Task SetUnixFileModeTest() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return; + } + + var sourceContent = "Test content"; + File.WriteAllText(restFilePath, sourceContent); + + var expected = UnixFileMode.UserWrite | UnixFileMode.UserRead; + + File.SetUnixFileMode(restFilePath, expected); + + var result = File.GetUnixFileMode(restFilePath); + + await Assert.That(result).IsEqualTo(expected); + } + + [UnsupportedOSPlatform("windows")] + [Test] + public async Task GetSetUnixFileMode_PathWithSpaces() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return; + } + + var directory = Path.Combine(Path.GetTempPath(), "polyfill mode " + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + var path = Path.Combine(directory, "it's a \"file\".txt"); + try + { + File.WriteAllText(path, "content"); + var expected = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead; + + File.SetUnixFileMode(path, expected); + + await Assert.That(File.GetUnixFileMode(path)).IsEqualTo(expected); + } + finally + { + Directory.Delete(directory, true); + } + } + + [UnsupportedOSPlatform("windows")] + [Test] + public async Task GetSetUnixFileMode_MissingFile_Throws() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return; + } + + var missing = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"), "missing.txt"); + + await Assert.That(() => File.GetUnixFileMode(missing)).Throws(); + await Assert.That(() => File.SetUnixFileMode(missing, UnixFileMode.UserRead)).Throws(); } #if !NET7_0_OR_GREATER @@ -744,265 +1005,4 @@ public async Task FileInfo_CreateAsHardLink_ThrowsIfTargetNotFound() await Assert.That(() => fileInfo.CreateAsHardLink("nonexistent.txt")).Throws(); } - - static string CreateReadLinesTestDirectory() - { - var directory = Path.Combine(Path.GetTempPath(), "PolyfillFileReadLines_" + Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(directory); - return directory; - } - - // File contents chosen around the reader's buffer sizes (1024 and 4096 bytes), so that lines end - // exactly on, just before and just after a buffer boundary, and line terminators get split by one. - static IEnumerable ReadLinesContents() - { - yield return ""; - yield return "\n"; - yield return "\r\n"; - yield return "\r"; - yield return "\n\n\n"; - yield return "single line without terminator"; - yield return "one\ntwo\r\nthree\rfour"; - yield return "one\ntwo\r\nthree\rfour\n"; - yield return "trailing blank lines\n\n\n"; - yield return "\n\nleading blank lines"; - yield return "a\u00e9\u4f60\U0001F30D\nb\u00e9\u4f60\U0001F30D\r\n"; - - foreach (var boundary in new[] {1024, 2048, 4096, 8192}) - { - foreach (var delta in new[] {-2, -1, 0, 1, 2}) - { - foreach (var terminator in new[] {"\n", "\r\n", "\r", ""}) - { - // the first line ends boundary + delta bytes into the file - var length = boundary + delta - terminator.Length; - yield return new string('x', length) + terminator; - yield return new string('x', length) + terminator + "next"; - yield return new string('x', length) + terminator + "next\n"; - } - } - } - - // many lines of the same length, so that buffer boundaries land on every position of a line - var builder = new StringBuilder(); - for (var index = 0; index < 5000; index++) - { - builder.Append("line ").Append(index % 10).Append("\r\n"); - } - - yield return builder.ToString(); - - // lines that are each exactly one buffer long - builder.Clear(); - for (var index = 0; index < 20; index++) - { - builder.Append('y', 1023).Append('\n'); - } - - yield return builder.ToString(); - - // one line much longer than any buffer - yield return new string('z', 100_000); - yield return new string('z', 100_000) + "\n" + new string('w', 50_000); - } - - [Test] - public async Task ReadAllLinesAsync_MatchesReadAllLines() - { - var directory = CreateReadLinesTestDirectory(); - try - { - var path = Path.Combine(directory, "lines.txt"); - var index = 0; - foreach (var content in ReadLinesContents()) - { - index++; - File.WriteAllText(path, content, new UTF8Encoding(false)); - var expected = File.ReadAllLines(path); - - var actual = await File.ReadAllLinesAsync(path); - - if (!actual.SequenceEqual(expected)) - { - throw new($"ReadAllLinesAsync differs from ReadAllLines for content {index} ({content.Length} chars): {actual.Length} lines rather than {expected.Length}"); - } - } - } - finally - { - Directory.Delete(directory, true); - } - } - - [Test] - public async Task ReadAllLinesAsync_Encodings_MatchReadAllLines() - { - var directory = CreateReadLinesTestDirectory(); - try - { - var path = Path.Combine(directory, "lines.txt"); - var builder = new StringBuilder(); - for (var index = 0; index < 3000; index++) - { - builder.Append("a\u00e9\u4f60\U0001F30D ").Append(index).Append(index % 2 == 0 ? "\n" : "\r\n"); - } - - var content = builder.ToString(); - var encodings = new Encoding[] - { - new UTF8Encoding(false), - new UTF8Encoding(true), - new UnicodeEncoding(false, true), - new UnicodeEncoding(true, true), - new UTF32Encoding(false, true) - }; - foreach (var encoding in encodings) - { - File.WriteAllText(path, content, encoding); - var expected = File.ReadAllLines(path, encoding); - - await Assert.That((await File.ReadAllLinesAsync(path, encoding)).SequenceEqual(expected)).IsTrue(); - - // a byte order mark overrides the encoding that was asked for - if (encoding.GetPreamble().Length > 0) - { - await Assert.That((await File.ReadAllLinesAsync(path)).SequenceEqual(expected)).IsTrue(); - await Assert.That((await File.ReadAllLinesAsync(path, Encoding.ASCII)).SequenceEqual(expected)).IsTrue(); - } - } - } - finally - { - Directory.Delete(directory, true); - } - } - - [Test] - public async Task ReadAllLinesAsync_CanceledToken_ThrowsAndReleasesFile() - { - var directory = CreateReadLinesTestDirectory(); - try - { - var path = Path.Combine(directory, "lines.txt"); - File.WriteAllText(path, "one\ntwo\n"); - using var cancelSource = new CancelSource(); - cancelSource.Cancel(); - - await Assert.That(async () => await File.ReadAllLinesAsync(path, cancelSource.Token)) - .Throws(); - - // the file is not left open - File.Delete(path); - await Assert.That(File.Exists(path)).IsFalse(); - } - finally - { - Directory.Delete(directory, true); - } - } - -#if FeatureAsyncInterfaces - [Test] - public async Task ReadLinesAsync_MatchesReadAllLines() - { - var directory = CreateReadLinesTestDirectory(); - try - { - var path = Path.Combine(directory, "lines.txt"); - var index = 0; - foreach (var content in ReadLinesContents()) - { - index++; - File.WriteAllText(path, content, new UTF8Encoding(false)); - var expected = File.ReadAllLines(path); - - var actual = new List(); - await foreach (var line in File.ReadLinesAsync(path)) - { - actual.Add(line); - } - - if (!actual.SequenceEqual(expected)) - { - throw new($"ReadLinesAsync differs from ReadAllLines for content {index} ({content.Length} chars): {actual.Count} lines rather than {expected.Length}"); - } - } - } - finally - { - Directory.Delete(directory, true); - } - } - - [Test] - public async Task ReadLinesAsync_CanceledWhileEnumerating_ThrowsAndReleasesFile() - { - var directory = CreateReadLinesTestDirectory(); - try - { - var path = Path.Combine(directory, "lines.txt"); - File.WriteAllLines(path, Enumerable.Range(0, 5000).Select(_ => "line " + _)); - using var source = new CancelSource(); - var read = new List(); - - await Assert.That(async () => - { - await foreach (var line in File.ReadLinesAsync(path, source.Token)) - { - read.Add(line); - if (read.Count == 10) - { - source.Cancel(); - } - } - }) - .Throws(); - - // The BCL only notices the cancellation at its next read from the file, so it may hand - // out a few more lines that it had already buffered. Either way the lines that were - // returned are the first ones, in order, and the enumeration stops well short of the end. - await Assert.That(read.Count >= 10).IsTrue(); - await Assert.That(read.Count < 1000).IsTrue(); - await Assert.That(read.SequenceEqual(Enumerable.Range(0, read.Count).Select(_ => "line " + _))).IsTrue(); - - // the file is not left open - File.Delete(path); - await Assert.That(File.Exists(path)).IsFalse(); - } - finally - { - Directory.Delete(directory, true); - } - } - - [Test] - public async Task ReadLinesAsync_StoppingEarly_ReleasesFile() - { - var directory = CreateReadLinesTestDirectory(); - try - { - var path = Path.Combine(directory, "lines.txt"); - File.WriteAllLines(path, Enumerable.Range(0, 5000).Select(_ => "line " + _)); - var read = new List(); - - await foreach (var line in File.ReadLinesAsync(path)) - { - read.Add(line); - if (read.Count == 3) - { - break; - } - } - - await Assert.That(read.SequenceEqual(new[] {"line 0", "line 1", "line 2"})).IsTrue(); - - File.Delete(path); - await Assert.That(File.Exists(path)).IsFalse(); - } - finally - { - Directory.Delete(directory, true); - } - } -#endif } \ No newline at end of file