using System.Globalization; using System.Text; namespace Khaemhat.Infrastructure.Files; /// How numbers and dates are written in a CSV file. public enum CsvNumberFormat { /// Italian Excel: decimal comma (1234,5), dates dd/MM/yyyy, booleans VERO/FALSO. Italian = 0, /// Machine readable: decimal point (1234.5), ISO 8601 dates, booleans true/false. Invariant = 1, } /// The options of a . The defaults suit Excel in Italian (ADR 0021). public sealed record CsvOptions { /// The field separator: ; by default, because Italian Excel uses the comma for decimals. public char Separator { get; init; } = ';'; /// Whether the file starts with the UTF-8 byte order mark, which Excel needs to read accented letters. public bool WriteByteOrderMark { get; init; } = true; /// How numbers, dates and booleans are formatted. public CsvNumberFormat NumberFormat { get; init; } = CsvNumberFormat.Italian; /// /// Whether text cells that a spreadsheet would read as a formula (starting with =, +, -, /// @, tab or carriage return) get a leading apostrophe (CSV injection, OWASP). Numbers are never changed. /// public bool ProtectFormulas { get; init; } = true; /// The line terminator: CRLF as RFC 4180 says. public string NewLine { get; init; } = "\r\n"; /// The Italian Excel defaults. public static CsvOptions Italian { get; } = new(); /// Comma separator, invariant numbers, no byte order mark: for other programs. public static CsvOptions Invariant { get; } = new() { Separator = ',', NumberFormat = CsvNumberFormat.Invariant, WriteByteOrderMark = false }; } /// /// Writes CSV files (RFC 4180) row by row (SPEC §2, §9.4). Fields with separator, quotes or line breaks are quoted and /// quotes doubled. Rows are buffered in memory and written to the stream when the buffer grows past a few KB: use the /// Async methods when the stream is an HTTP response, where synchronous writes are not allowed. /// /// /// /// await using var csv = new CsvWriter(response.Body); /// await csv.WriteRowAsync(["Codice", "Descrizione", "Importo"]); /// await csv.WriteRowAsync(["A1", "Vite M4", 12.5m]); /// /// public sealed class CsvWriter : IDisposable, IAsyncDisposable { private const int FlushThreshold = 16 * 1024; private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT"); private static readonly UTF8Encoding Utf8 = new(encoderShouldEmitUTF8Identifier: false); private readonly Stream _output; private readonly bool _leaveOpen; private readonly StringBuilder _buffer = new(); private bool _rowHasFields; private bool _preambleWritten; private bool _disposed; /// Creates a writer. /// The stream that receives the file. /// The options; for . /// Whether to leave open on dispose. public CsvWriter(Stream output, CsvOptions? options = null, bool leaveOpen = false) { ArgumentNullException.ThrowIfNull(output); _output = output; _leaveOpen = leaveOpen; Options = options ?? CsvOptions.Italian; if (Options.Separator is '"' or '\r' or '\n') { throw new ArgumentException("The separator cannot be a quote or a line break.", nameof(options)); } } /// The options. public CsvOptions Options { get; } /// The number of rows completed. public long RowCount { get; private set; } /// Formats a text field: formula protection, then quoting when needed. /// The text. /// The options. /// The field as written in the file. public static string EscapeText(string? value, CsvOptions options) { ArgumentNullException.ThrowIfNull(options); if (string.IsNullOrEmpty(value)) { return string.Empty; } if (options.ProtectFormulas && value[0] is '=' or '+' or '-' or '@' or '\t' or '\r') { value = "'" + value; } return Quote(value, options.Separator); } /// Formats a value as it would be written (numbers and dates by ). /// The value. /// The options. /// The field as written in the file. public static string FormatValue(object? value, CsvOptions options) { ArgumentNullException.ThrowIfNull(options); var culture = options.NumberFormat == CsvNumberFormat.Italian ? Italian : CultureInfo.InvariantCulture; var italian = options.NumberFormat == CsvNumberFormat.Italian; var text = value switch { null => null, string s => s, bool b => italian ? (b ? "VERO" : "FALSO") : (b ? "true" : "false"), DateOnly d => d.ToString(italian ? "dd/MM/yyyy" : "yyyy-MM-dd", CultureInfo.InvariantCulture), DateTime d when d.TimeOfDay == TimeSpan.Zero => d.ToString(italian ? "dd/MM/yyyy" : "yyyy-MM-dd", CultureInfo.InvariantCulture), DateTime d => d.ToString(italian ? "dd/MM/yyyy HH:mm:ss" : "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture), DateTimeOffset d => d.ToString(italian ? "dd/MM/yyyy HH:mm:ss" : "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture), decimal m => m.ToString("0.############################", culture), double x when double.IsFinite(x) => x.ToString("0.###############", culture), float x when float.IsFinite(x) => x.ToString("0.#######", culture), double or float => string.Empty, IFormattable f => f.ToString(null, culture), _ => value.ToString(), }; // Only text can carry a formula: numbers, dates and booleans are written as they are. return value is string or char or Enum || value is not IFormattable and not bool ? EscapeText(text, options) : Quote(text ?? string.Empty, options.Separator); } /// Adds a field to the current row. /// Text, number, date, boolean or (empty field). /// This writer. public CsvWriter WriteField(object? value) { ObjectDisposedException.ThrowIf(_disposed, this); if (_rowHasFields) { _buffer.Append(Options.Separator); } _buffer.Append(FormatValue(value, Options)); _rowHasFields = true; return this; } /// Ends the current row; writes to the stream synchronously when the buffer is large. public void EndRow() { CompleteRow(); if (_buffer.Length >= FlushThreshold) { Flush(); } } /// Ends the current row; writes to the stream when the buffer is large. /// Cancellation. /// A task. public async ValueTask EndRowAsync(CancellationToken cancellationToken = default) { CompleteRow(); if (_buffer.Length >= FlushThreshold) { await FlushAsync(cancellationToken).ConfigureAwait(false); } } /// Writes a whole row (synchronous stream). /// The fields. public void WriteRow(params IEnumerable values) { ArgumentNullException.ThrowIfNull(values); foreach (var value in values) { WriteField(value); } EndRow(); } /// Writes a whole row. /// The fields. /// Cancellation. /// A task. public ValueTask WriteRowAsync(IEnumerable values, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(values); foreach (var value in values) { WriteField(value); } return EndRowAsync(cancellationToken); } /// Writes the buffered rows to the stream synchronously. public void Flush() { var bytes = TakeBytes(); if (bytes.Length > 0) { _output.Write(bytes); } _output.Flush(); } /// Writes the buffered rows to the stream. /// Cancellation. /// A task. public async Task FlushAsync(CancellationToken cancellationToken = default) { var bytes = TakeBytes(); if (bytes.Length > 0) { await _output.WriteAsync(bytes, cancellationToken).ConfigureAwait(false); } await _output.FlushAsync(cancellationToken).ConfigureAwait(false); } /// Ends a pending row, writes the buffer synchronously and closes the stream unless left open. public void Dispose() { if (_disposed) { return; } if (_rowHasFields) { CompleteRow(); } Flush(); _disposed = true; if (!_leaveOpen) { _output.Dispose(); } } /// Ends a pending row, writes the buffer and closes the stream unless left open. /// A task. public async ValueTask DisposeAsync() { if (_disposed) { return; } if (_rowHasFields) { CompleteRow(); } await FlushAsync().ConfigureAwait(false); _disposed = true; if (!_leaveOpen) { await _output.DisposeAsync().ConfigureAwait(false); } } private static string Quote(string value, char separator) { var needsQuotes = value.Length > 0 && (value.Contains(separator, StringComparison.Ordinal) || value.AsSpan().IndexOfAny("\"\r\n") >= 0 || char.IsWhiteSpace(value[0]) || char.IsWhiteSpace(value[^1])); return needsQuotes ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value; } private void CompleteRow() { ObjectDisposedException.ThrowIf(_disposed, this); _buffer.Append(Options.NewLine); _rowHasFields = false; RowCount++; } private byte[] TakeBytes() { var preamble = !_preambleWritten && Options.WriteByteOrderMark ? Encoding.UTF8.Preamble.ToArray() : []; _preambleWritten = true; if (_buffer.Length == 0 && preamble.Length == 0) { return []; } var text = _buffer.ToString(); _buffer.Clear(); var bytes = new byte[preamble.Length + Utf8.GetByteCount(text)]; preamble.CopyTo(bytes, 0); Utf8.GetBytes(text, 0, text.Length, bytes, preamble.Length); return bytes; } }