| | | 1 | | using ArturRios.Data.Export.Abstractions; |
| | | 2 | | using ArturRios.Data.Export.Configuration; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | |
| | | 5 | | namespace ArturRios.Data.Export.Exporters; |
| | | 6 | | |
| | | 7 | | /// <summary>Writes records as delimited text using the shared column map and RFC 4180 quoting.</summary> |
| | | 8 | | /// <remarks> |
| | | 9 | | /// Quoting follows RFC 4180: a field is quoted when it holds the delimiter, a double quote or a line |
| | | 10 | | /// break, and an embedded quote is doubled. The delimiter and the line terminator are not fixed to the |
| | | 11 | | /// RFC's comma and CRLF - the delimiter comes from the options and lines end with the platform's |
| | | 12 | | /// newline - so the output is RFC 4180 only when those happen to match. |
| | | 13 | | /// </remarks> |
| | | 14 | | /// <typeparam name="T">The record type.</typeparam> |
| | | 15 | | /// <param name="options">CSV options.</param> |
| | | 16 | | /// <param name="logger">Optional logger; see <see cref="ExporterBase{T}" />.</param> |
| | | 17 | | public class CsvExporter<T>(CsvOptions options, ILogger<CsvExporter<T>>? logger = null) |
| | 16 | 18 | | : ExporterBase<T>(logger) where T : class |
| | | 19 | | { |
| | | 20 | | /// <inheritdoc /> |
| | | 21 | | protected override async Task WriteCoreAsync(IEnumerable<T> data, Stream destination, CancellationToken ct) |
| | | 22 | | { |
| | 12 | 23 | | var columns = ColumnMap.For<T>(); |
| | 12 | 24 | | var writer = new StreamWriter(destination, options.Encoding, leaveOpen: true); |
| | | 25 | | |
| | 12 | 26 | | await using var writerScope = writer.ConfigureAwait(false); |
| | | 27 | | |
| | 12 | 28 | | if (options.IncludeHeader) |
| | | 29 | | { |
| | 10 | 30 | | await writer.WriteLineAsync(string.Join(options.Delimiter, |
| | 40 | 31 | | columns.Select(c => Escape(c.Header, options.Delimiter)))).ConfigureAwait(false); |
| | | 32 | | } |
| | | 33 | | |
| | 44 | 34 | | foreach (var item in data) |
| | | 35 | | { |
| | 10 | 36 | | ct.ThrowIfCancellationRequested(); |
| | 10 | 37 | | await writer.WriteLineAsync(string.Join(options.Delimiter, |
| | 40 | 38 | | columns.Select(c => Escape(ValueRenderer.Render(c.Getter(item)), options.Delimiter)))).ConfigureAwait(fa |
| | | 39 | | } |
| | | 40 | | |
| | 12 | 41 | | await writer.FlushAsync(ct).ConfigureAwait(false); |
| | 12 | 42 | | } |
| | | 43 | | |
| | | 44 | | private static string Escape(string field, char delimiter) |
| | | 45 | | { |
| | 60 | 46 | | var mustQuote = field.Contains(delimiter) || field.Contains('"') || field.Contains('\n') || field.Contains('\r') |
| | 60 | 47 | | return mustQuote ? $"\"{field.Replace("\"", "\"\"")}\"" : field; |
| | | 48 | | } |
| | | 49 | | } |