Path: redb-route/redb.Route.DataFormats.Csv/CsvDataFormat.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.DataFormats.Csv/CsvDataFormat.cs ---- using System.Collections; using CsvHelper; using CsvHelper.Configuration; using redb.Route.Abstractions; namespace redb.Route.DataFormats.Csv; /// /// CSV (CsvHelper). Marshals POCO collections (header from property /// names), dictionaries (header from keys), raw rows (string[] / object[], no header) or a /// single POCO; unmarshals to List<T> / T[] / IEnumerable<T>, to /// List<Dictionary<string,string>> (with header) or List<string[]> (without), /// or to a single T. Errors name the format. /// public sealed class CsvDataFormat : IMessageSerializer { /// Content type the format is registered under. public const string DefaultContentType = "text/csv"; /// The name the format answers to in markup, <marshal format="csv"/>, as Apache Camel names it; AddCsvDataFormat() registers it. public const string Name = "csv"; private readonly CsvDataFormatOptions _options; /// Creates the format with the given options (defaults when null). public CsvDataFormat(CsvDataFormatOptions? options = null) => _options = options ?? new CsvDataFormatOptions(); /// The options in effect. public CsvDataFormatOptions Options => _options; /// public string ContentType => DefaultContentType; /// public IReadOnlyCollection MediaTypes => [DefaultContentType, "application/csv"]; private CsvConfiguration Configuration(bool forWriting) { var configuration = new CsvConfiguration(_options.Culture) { Delimiter = _options.Delimiter, HasHeaderRecord = _options.HasHeaderRecord, Quote = _options.Quote, TrimOptions = _options.TrimFields ? TrimOptions.Trim : TrimOptions.None, MissingFieldFound = null, HeaderValidated = null, }; // NewLine is a writer setting: when set on a reader CsvHelper stops auto-detecting \r\n / \n / \r. if (forWriting) configuration.NewLine = _options.NewLine; return configuration; } // ── Marshal ─────────────────────────────────────────────────────────────── /// public byte[] Serialize(T value) { switch (value) { case null: return []; case byte[] bytes: return bytes; case string text: return _options.Encoding.GetBytes(text); } try { using var writer = new StringWriter(_options.Culture); using (var csv = new CsvWriter(writer, Configuration(forWriting: true), leaveOpen: true)) { switch (value) { case IEnumerable maps: WriteMaps(csv, maps); break; case IEnumerable rows: WriteRows(csv, rows); break; case IEnumerable rows: WriteRows(csv, rows); break; case IEnumerable records: csv.WriteRecords(records); break; default: csv.WriteRecords(new[] { value }); break; } } return _options.Encoding.GetBytes(writer.ToString()); } catch (Exception ex) when (ex is CsvHelperException or InvalidOperationException or ArgumentException) { throw new InvalidOperationException($"CSV data format: cannot marshal {value.GetType().Name} ({ex.Message}).", ex); } } private void WriteMaps(CsvWriter csv, IEnumerable maps) { // The header is the union of every row's keys in first-seen order: a column that only a later // row carries must not be dropped because the first row happened not to have it. var rows = maps.ToList(); var header = new List(); var seen = new HashSet(StringComparer.Ordinal); foreach (var map in rows) foreach (var key in map.Keys) { var name = key?.ToString() ?? string.Empty; if (seen.Add(name)) header.Add(name); } if (_options.HasHeaderRecord) { foreach (var name in header) csv.WriteField(name); csv.NextRecord(); } foreach (var map in rows) { foreach (var name in header) csv.WriteField(map.Contains(name) ? map[name] : null); csv.NextRecord(); } } private static void WriteRows(CsvWriter csv, IEnumerable> rows) { foreach (var row in rows) { foreach (var cell in row) csv.WriteField(cell); csv.NextRecord(); } } // ── Unmarshal ───────────────────────────────────────────────────────────── /// public T? Deserialize(byte[] data) => (T?)Deserialize(data, typeof(T)); /// public object? Deserialize(byte[] data, Type type) { ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(type); var text = _options.Encoding.GetString(data); if (type == typeof(string)) return text; try { using var reader = new StringReader(text); using var csv = new CsvReader(reader, Configuration(forWriting: false)); var element = CollectionElement(type); if (element is null) return ReadSingle(csv, type); var items = ReadMany(csv, element); return ToCollection(type, element, items); } catch (Exception ex) when (ex is CsvHelperException or FormatException or InvalidOperationException or ArgumentException) { throw new InvalidOperationException($"CSV data format: cannot unmarshal to {type.Name} ({ex.Message}).", ex); } } private object? ReadSingle(CsvReader csv, Type type) { if (type == typeof(object) || IsMapType(type)) return ReadMany(csv, type).FirstOrDefault(); if (type == typeof(string[])) return ReadMany(csv, type).FirstOrDefault(); return csv.GetRecords(type).Cast().FirstOrDefault(); } private List ReadMany(CsvReader csv, Type element) { if (element == typeof(string[])) return ReadRows(csv, skipHeader: _options.HasHeaderRecord); if (element == typeof(object) || IsMapType(element)) return _options.HasHeaderRecord ? ReadMaps(csv, element) : ReadRows(csv, skipHeader: false); return csv.GetRecords(element).Cast().ToList(); } /// Raw rows; with a header record configured, the header line is data for nobody and is skipped. private static List ReadRows(CsvReader csv, bool skipHeader) { var rows = new List(); if (skipHeader && !csv.Read()) return rows; while (csv.Read()) rows.Add(csv.Parser.Record?.ToArray() ?? []); return rows; } private static List ReadMaps(CsvReader csv, Type element) { var rows = new List(); if (!csv.Read()) return rows; csv.ReadHeader(); var header = csv.HeaderRecord ?? []; var objectValues = element == typeof(object) || (element.IsGenericType && element.GetGenericArguments()[1] == typeof(object)); while (csv.Read()) { if (objectValues) { var map = new Dictionary(StringComparer.OrdinalIgnoreCase); for (var i = 0; i < header.Length; i++) map[header[i]] = csv.GetField(i); rows.Add(map); } else { var map = new Dictionary(StringComparer.OrdinalIgnoreCase); for (var i = 0; i < header.Length; i++) map[header[i]] = csv.GetField(i) ?? string.Empty; rows.Add(map); } } return rows; } /// Element type when is a supported collection shape; otherwise null (single record). private static Type? CollectionElement(Type type) { if (type == typeof(string[])) return null; // one raw row if (type.IsArray) return type.GetElementType(); if (!type.IsGenericType) return type == typeof(IEnumerable) ? typeof(object) : null; var definition = type.GetGenericTypeDefinition(); if (definition == typeof(List<>) || definition == typeof(IList<>) || definition == typeof(IEnumerable<>) || definition == typeof(ICollection<>) || definition == typeof(IReadOnlyList<>) || definition == typeof(IReadOnlyCollection<>)) return type.GetGenericArguments()[0]; return null; } private static bool IsMapType(Type type) { if (!type.IsGenericType) return false; var definition = type.GetGenericTypeDefinition(); return (definition == typeof(Dictionary<,>) || definition == typeof(IDictionary<,>) || definition == typeof(IReadOnlyDictionary<,>)) && type.GetGenericArguments()[0] == typeof(string); } private static object ToCollection(Type collectionType, Type element, List items) { if (collectionType.IsArray) { var array = Array.CreateInstance(element, items.Count); for (var i = 0; i < items.Count; i++) array.SetValue(items[i], i); return array; } var listType = typeof(List<>).MakeGenericType(element == typeof(object) && items.Count > 0 && items[0] is IDictionary ? typeof(object) : element); var list = (IList)Activator.CreateInstance(listType)!; foreach (var item in items) list.Add(item); return list; } }