| | | 1 | | using ArturRios.Data.Export.Configuration; |
| | | 2 | | using ArturRios.Output; |
| | | 3 | | |
| | | 4 | | namespace ArturRios.Data.Export.Exporters; |
| | | 5 | | |
| | | 6 | | /// <summary>Writes one line per record: default <see cref="object.ToString" />, or a custom selector.</summary> |
| | | 7 | | /// <typeparam name="T">The record type.</typeparam> |
| | | 8 | | /// <param name="options">TXT options.</param> |
| | 6 | 9 | | public class TxtExporter<T>(TxtOptions options) : ExporterBase<T> where T : class |
| | | 10 | | { |
| | | 11 | | /// <inheritdoc /> |
| | | 12 | | protected override Task WriteCoreAsync(IEnumerable<T> data, Stream destination, CancellationToken ct) => |
| | 3 | 13 | | WriteLinesAsync(data, destination, item => item?.ToString() ?? string.Empty, ct); |
| | | 14 | | |
| | | 15 | | /// <summary>Writes each record on its own line using <paramref name="lineSelector" />.</summary> |
| | | 16 | | public Task<ProcessOutput> WriteAsync(IEnumerable<T> data, Stream destination, Func<T, string> lineSelector, |
| | | 17 | | CancellationToken ct = default) => |
| | 3 | 18 | | GuardedWriteAsync(data, destination, stream => WriteLinesAsync(data, stream, lineSelector, ct)); |
| | | 19 | | |
| | | 20 | | /// <summary>Writes each record on its own line to a file using <paramref name="lineSelector" />.</summary> |
| | | 21 | | public Task<ProcessOutput> WriteToFileAsync(IEnumerable<T> data, string path, Func<T, string> lineSelector, |
| | | 22 | | CancellationToken ct = default) => |
| | 0 | 23 | | GuardedFileAsync(data, path, stream => WriteLinesAsync(data, stream, lineSelector, ct)); |
| | | 24 | | |
| | | 25 | | private async Task WriteLinesAsync(IEnumerable<T> data, Stream destination, Func<T, string> lineSelector, |
| | | 26 | | CancellationToken ct) |
| | 3 | 27 | | { |
| | 3 | 28 | | await using var writer = new StreamWriter(destination, options.Encoding, leaveOpen: true); |
| | | 29 | | |
| | 15 | 30 | | foreach (var item in data) |
| | 3 | 31 | | { |
| | 3 | 32 | | ct.ThrowIfCancellationRequested(); |
| | 3 | 33 | | await writer.WriteAsync(lineSelector(item)); |
| | 3 | 34 | | await writer.WriteAsync(options.NewLine); |
| | 3 | 35 | | } |
| | | 36 | | |
| | 3 | 37 | | await writer.FlushAsync(ct); |
| | 3 | 38 | | } |
| | | 39 | | } |