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