Schemas, formats, and cultures

A schema controls the type and conversion settings used by the data reader. It does not select source columns or bind CSV constructor parameters by name. Object mapping is a separate path; JSON projection selects properties.

Defining a schema

An indexed schema follows column positions. A named schema follows reader field names, which is useful when labeled records change order. Name matching is case-sensitive. A schema validates values when conversion is requested; it does not guarantee the whole file is valid before reading.

using System.Globalization;
using System.Text;
using PocketCsvReader.Configuration;

var csv = new CsvReaderBuilder()
    .WithDialect(d => d.WithDelimiter(';').WithHeader().WithLineTerminator("\n"))
    .WithSchema(s => s.Named()
        .WithTemporalField<DateOnly>("Date", f => f.WithFormat("dd/MM/yyyy"))
        .WithNumberField<decimal>("Amount", f => f.WithFormat(n =>
            n.WithDecimalChar(',').WithoutGroupChar())))
    .Build();
using var stream = new MemoryStream(Encoding.UTF8.GetBytes("Date;Amount\n30/10/2026;149,95\n"));
using var reader = csv.ToDataReader(stream);
while (reader.Read())
    Console.WriteLine(FormattableString.Invariant(
        $"{reader.GetFieldValue<DateOnly>(0):yyyy-MM-dd}: {reader.GetDecimal(1):F2}"));
2026-10-30: 149.95

For positions, use new SchemaDescriptorBuilder().Indexed().WithField<int>().WithField<string>().Build(). Supply the result to WithSchema. Named schemas use Named().WithField<int>("Id").

Using field formatting and format descriptors

Use WithTemporalField<T> for a temporal pattern, WithNumberField<T> for decimal/group separators, and WithIntegerField<T> for integer settings. Use WithField<T> with WithFormat(pattern, formatProvider) for custom parser formats. Formats use their configured provider; built-in schema builders supply invariant defaults. A fixed date format avoids relying on machine culture.

Numeric formatting

NumberFieldDescriptorBuilder.WithFormat receives a NumberFormatDescriptorBuilder. Set WithDecimalChar, WithGroupChar, or WithoutGroupChar inside that callback. The type is named Number, not Numeric.

Migrating from WithCustomField

Deprecated. WithCustomField still works and now emits a compiler warning. It will be removed in PocketCsvReader 3.0. Replace it with WithField in named and indexed schemas. Keep the same type, column name or position, and inline configuration callback.

For a named column, use WithField<YearMonth>("Month", f => f.WithFormat("yyyy-MM")). For an indexed column, use WithField<YearMonth>(f => f.WithFormat("yyyy-MM")). The optional second argument to WithFormat supplies the format provider to parsers that support it. A field callback declared separately as Func<CustomFieldDescriptorBuilder, CustomFieldDescriptorBuilder> should use Func<FieldDescriptorBuilder, FieldDescriptorBuilder> when passed to WithField.

Providing a custom parser

Register an explicitly typed span lambda on a field, for example WithField<int>(f => f.WithParser((ReadOnlySpan<char> text) => int.Parse(text, CultureInfo.InvariantCulture))). For a type shared by multiple fields, use a runtime parser. Field parsers take precedence over field formats and runtime parsers. A field format can take precedence over a runtime type parser, so inspect field settings when a runtime override appears ineffective.

Custom types must be defined by the application. For a coordinate type, define its public constructor and conversion logic explicitly rather than copying an undefined Point snippet. Custom parsers contains a complete custom-type example.

Arrays

Configure array syntax in the CSV dialect, then declare a one-dimensional CLR array such as WithField<int[]>("Scores"). GetValue, indexers and GetValues return a typed array through the element-parser path. GetArray<T> also works without a whole-array schema declaration. A whole-array custom parser takes precedence over element parsing.

Declaring an array does not turn scalar text into an array. Enumerable types are not array declarations; multidimensional CLR arrays are unsupported. Null elements and conversion failures follow the relevant array getters. JSON arrays have their own source grammar; see JSON and NDJSON.

Hex and Base64 fields

Choose the decoder that matches the encoding used by the CSV producer. PocketCsvReader does not guess the encoding. A plain WithField<byte[]>("Payload") uses the dialect’s array syntax, such as [0|255|44] with the array delimiter | and brackets configured.

Field configuration Accepted text
f => f.FromHex() Two hex digits per byte, in upper or lower case. Enter 00FF2C as a continuous sequence without a 0x prefix or separators.
f => f.FromBase64() Standard Base64 using + and /, with = padding when required. The decoder ignores spaces, tabs, and line breaks present in the field value.

Both shortcuts are available on the shared builder and require a field declared as byte[]. Calling either shortcut for another field type throws InvalidOperationException during schema configuration. For an indexed schema, use Indexed().WithField<byte[]>(f => f.FromHex()) or the corresponding FromBase64() form.

using System.Text;
using PocketCsvReader.Configuration;

var csv = new CsvReaderBuilder()
    .WithDialect(d => d.WithDelimiter(',').WithHeader().WithLineTerminator("\n"))
    .WithSchema(s => s.Named()
        .WithField<byte[]>("HexPayload", f => f.FromHex())
        .WithField<byte[]>("Base64Payload", f => f.FromBase64()))
    .Build();

using var stream = new MemoryStream(Encoding.UTF8.GetBytes(
    "HexPayload,Base64Payload\n00FF2C,AP8s\n"));
using var reader = csv.ToDataReader(stream);
while (reader.Read())
{
    Console.WriteLine(Convert.ToHexString((byte[])reader["HexPayload"]));
    Console.WriteLine(Convert.ToHexString((byte[])reader["Base64Payload"]));
}
00FF2C
00FF2C

Each shortcut registers a field parser for the whole cell. Once on a row, use IsValid("HexPayload") to check whether the cell can be decoded. Reading malformed encoded text through the indexer or GetValue throws FormatException. An empty string passed to either decoder yields an empty byte array. Values interpreted as null or missing follow the reader’s null and missing value rules.

The decoder returns raw bytes. For a payload such as Well-Known Binary (WKB), use a WKB reader to interpret those bytes as geometry.

Base64url

Use FromBase64Url() for the URL-safe alphabet, which uses - and _. The decoder accepts padded and unpadded input and ignores spaces, tabs, and line breaks in the cell value. Like the other binary shortcuts, it requires a byte[] field and reports malformed input through IsValid() and FormatException.

using System.Text;
using PocketCsvReader.Configuration;

var csv = new CsvReaderBuilder()
    .WithDialect(d => d.WithDelimiter(',').WithHeader().WithLineTerminator("\n"))
    .WithSchema(s => s.Named()
        .WithField<byte[]>("Payload", f => f.FromBase64Url()))
    .Build();

using var stream = new MemoryStream(Encoding.UTF8.GetBytes("Payload\n-_8\n"));
using var reader = csv.ToDataReader(stream);
while (reader.Read())
    Console.WriteLine(Convert.ToHexString((byte[])reader["Payload"]));
FBFF

Base32 and Base32hex fields

Use FromBase32() for the RFC 4648 alphabet A–Z, 2–7 and FromBase32Hex() for the extended hex alphabet 0–9, A–V. Both accept upper- and lowercase ASCII letters and require standard = padding for a partial eight-character group. Whitespace, misplaced padding, and nonzero unused bits are invalid. RFC 4648

using System.Text;
using PocketCsvReader.Configuration;

var csv = new CsvReaderBuilder()
    .WithDialect(d => d.WithDelimiter(',').WithHeader().WithLineTerminator("\n"))
    .WithSchema(s => s.Named()
        .WithField<byte[]>("Base32Payload", f => f.FromBase32())
        .WithField<byte[]>("Base32HexPayload", f => f.FromBase32Hex()))
    .Build();

using var stream = new MemoryStream(Encoding.UTF8.GetBytes(
    "Base32Payload,Base32HexPayload\nMZXQ====,CPNG====\n"));
using var reader = csv.ToDataReader(stream);
while (reader.Read())
{
    Console.WriteLine(Encoding.ASCII.GetString((byte[])reader["Base32Payload"]));
    Console.WriteLine(Encoding.ASCII.GetString((byte[])reader["Base32HexPayload"]));
}
fo
fo

Both shortcuts require a byte[] field. Use IsValid() on the current row to check encoded text before reading it. A malformed value throws FormatException when read.

Validation and inference

Use IsValid to check a cell against its current declared/inferred type. Use inference to discover candidate settings from a sample, then review diagnostics before applying them. Null and missing values explains the different cases that a schema alone does not normalize.


Profiles and builders
Custom parsers