CsvSerializerOptions Class

Options that control how CsvSerializer reads and writes records.

public sealed class CsvSerializerOptions

Remarks

The options are immutable, and the metadata of the types is cached in the instance: reuse the same instance rather than creating one for each call. Use CsvSerializerOptions to create a copy with other values.

Constructors

NameDescription
CsvSerializerOptions()Initializes a new instance of the CsvSerializerOptions class with the default values.
CsvSerializerOptions(CsvSerializerOptions)Initializes a new instance of the CsvSerializerOptions class with the values of other options.

CsvSerializerOptions overloads

CsvSerializerOptions()

CsvSerializerOptions.cs

Initializes a new instance of the CsvSerializerOptions class with the default values.

public CsvSerializerOptions()

CsvSerializerOptions(CsvSerializerOptions)

CsvSerializerOptions.cs

Initializes a new instance of the CsvSerializerOptions class with the values of other options.

public CsvSerializerOptions(CsvSerializerOptions options)
Parameters
options CsvSerializerOptions
The options to copy.

Properties

NameDescription
BadDataHandlerGets the method called for malformed data, which decides whether the serializer throws, accepts the data, or skips the record. Default is null.
BufferSizeGets the size of the buffers of the readers and the writers. Default is 16384.
CommentCharacterGets the character that starts a comment line, or null when the data has no comments. Default is null.
ConvertersGets the converters used before the built-in converters. Default is an empty list.
DefaultGets the default options.
DeserializationErrorHandlerGets the method called when a record cannot be converted to an object, which decides whether the serializer throws, ignores the error, or skips the record. Default is null.
EscapeFormulasGets a value indicating whether string values that a spreadsheet would run as a formula are escaped. Default is false.
FormatProviderGets the format provider used to parse and format values. Default is null, which means CultureInfo.InvariantCulture.
HasHeaderRowGets a value indicating whether the first row holds the names of the columns. Default is true.
IncludeFieldsGets a value indicating whether public fields are serialized. Default is false.
MaxDegreeOfParallelismGets the maximum number of threads that convert the records to objects when reading data. Default is 1.
MaxRowLengthGets the maximum length of a row read from a TextReader or a Stream. Default is 16777216.
MissingColumnHandlingGets how a member without a column is handled when reading data with a header row. Default is CsvMissingColumnHandling.Ignore.
NewLineGets the string written at the end of each row. Default is \r\n.
PropertyNameCaseInsensitiveGets a value indicating whether the names of the columns are matched ignoring case. Default is false.
PropertyNamingPolicyGets the policy that converts the names of the members to the names of the columns, or null to use the names of the members. Default is null.
QuoteGets the character that quotes values. Default is ". When null, values are never quoted.
QuoteModeGets when values are quoted. Default is CsvQuoteMode.AsNeeded.
SeparatorGets the character that separates the values of a row. Default is ,.
StrictGets a value indicating whether invalid quoting throws a CsvException. Default is false.
TrimGets which spaces are removed from the values read. Default is CsvTrimOptions.None.
TypeInfoResolverGets the resolver of the metadata of the types, such as a generated CsvSerializerContext. Default is null: the metadata is created with reflection.
UnmappedColumnHandlingGets how a column without a member is handled when reading data. Default is CsvUnmappedColumnHandling.Ignore.

Gets the method called for malformed data, which decides whether the serializer throws, accepts the data, or skips the record. Default is null.

public CsvBadDataHandler? BadDataHandler { get; init; }

Property value

CsvBadDataHandler?

Remarks

See CsvReaderOptions.BadDataHandler. To handle the values that cannot be converted, use CsvSerializerOptions.DeserializationErrorHandler.

Gets the size of the buffers of the readers and the writers. Default is 16384.

public int BufferSize { get; init; }

Property value

int

CommentCharacter

CsvSerializerOptions.cs

Gets the character that starts a comment line, or null when the data has no comments. Default is null.

public char? CommentCharacter { get; init; }

Property value

char?

Gets the converters used before the built-in converters. Default is an empty list.

public IReadOnlyList<CsvConverter> Converters { get; init; }

Gets the default options.

public static CsvSerializerOptions Default { get; }

Property value

CsvSerializerOptions

DeserializationErrorHandler

CsvSerializerOptions.cs

Gets the method called when a record cannot be converted to an object, which decides whether the serializer throws, ignores the error, or skips the record. Default is null.

public CsvDeserializationErrorHandler? DeserializationErrorHandler { get; init; }

Property value

CsvDeserializationErrorHandler?

Remarks

The handler is called for the errors that throw a CsvException without it (see CsvDeserializationErrorKind): a value that cannot be converted, a missing value or column for a required member, and the missing and unmapped columns when CsvSerializerOptions.MissingColumnHandling or CsvSerializerOptions.UnmappedColumnHandling is Throw. When it is null, the serializer throws.

A record can have several errors, reported one by one until the handler returns CsvDeserializationErrorAction.SkipRecord. The errors of the header row are reported when the first record is read. The exceptions thrown by the members, the constructors and the callbacks of the type are not reported. The handler may throw its own exception, which ends the reading.

The handler is used by the reflection-based metadata and by the generated CsvSerializerContext alike.

Example

var errors = new List<string>();
var options = new CsvSerializerOptions
{
    DeserializationErrorHandler = context =>
    {
        errors.Add($"line {context.LineNumber}: '{context.RawValue}' is not a valid {context.MemberName}");
        return CsvDeserializationErrorAction.SkipRecord; // or Ignore to keep the default value, or Throw
    },
};

var products = CsvSerializer.Deserialize<Product>("Id,Name,Price\n1,Keyboard,49.90\nx,Mouse,19.99\n3,Screen,199", options);

Assert.Equal(["Keyboard", "Screen"], products.Select(p => p.Name));
Assert.Equal(["line 3: 'x' is not a valid Id"], errors);

Gets a value indicating whether string values that a spreadsheet would run as a formula are escaped. Default is false.

public bool EscapeFormulas { get; init; }

Property value

bool

Remarks

Gets the format provider used to parse and format values. Default is null, which means CultureInfo.InvariantCulture.

public IFormatProvider? FormatProvider { get; init; }

Property value

IFormatProvider?

Gets a value indicating whether the first row holds the names of the columns. Default is true.

public bool HasHeaderRow { get; init; }

Property value

bool

Remarks

When true, the columns are read by name and the header row is written. Otherwise, the columns are read and written by position.

Gets a value indicating whether public fields are serialized. Default is false.

public bool IncludeFields { get; init; }

Property value

bool

MaxDegreeOfParallelism

CsvSerializerOptions.cs

Gets the maximum number of threads that convert the records to objects when reading data. Default is 1.

public int MaxDegreeOfParallelism { get; init; }

Property value

int 1 to convert the records on the calling thread, a larger value to convert them on the thread pool, or -1 to use Environment.ProcessorCount.

Exceptions

ArgumentOutOfRangeException
The value is 0 or less than -1.

Remarks

When larger than 1, the data is still split into records on the calling thread, and the records are converted to objects on the thread pool, in batches of a few hundred records; the calling thread converts the next batch itself when no thread of the pool has started it. The objects are returned in the order of the records, and the exceptions are the same as when reading the records one by one. The enumerable overloads read a few batches ahead of the objects they return. The gain is largest when converting the values takes time, such as numbers and dates, and smallest when strings are most of the values: the garbage collector limits their allocation, less so the server garbage collector. Splitting the data on one thread limits the gain to a few times, whatever the number of processors.

The constructors, the setters, the converters and the callbacks of the records are called from several threads at the same time. The CsvSerializerOptions.DeserializationErrorHandler is not called by two threads at the same time, but it can be called for the records in another order, and for records after the error that ends the reading. The CsvSerializerOptions.BadDataHandler is called on the calling thread. The browser and WASI convert the records on the calling thread.

Gets the maximum length of a row read from a TextReader or a Stream. Default is 16777216.

public int MaxRowLength { get; init; }

Property value

int

MissingColumnHandling

CsvSerializerOptions.cs

Gets how a member without a column is handled when reading data with a header row. Default is CsvMissingColumnHandling.Ignore.

public CsvMissingColumnHandling MissingColumnHandling { get; init; }

Gets the string written at the end of each row. Default is \r\n.

public string NewLine { get; init; }

Property value

string

PropertyNameCaseInsensitive

CsvSerializerOptions.cs

Gets a value indicating whether the names of the columns are matched ignoring case. Default is false.

public bool PropertyNameCaseInsensitive { get; init; }

Property value

bool

PropertyNamingPolicy

CsvSerializerOptions.cs

Gets the policy that converts the names of the members to the names of the columns, or null to use the names of the members. Default is null.

public CsvNamingPolicy? PropertyNamingPolicy { get; init; }

Property value

CsvNamingPolicy?

Gets the character that quotes values. Default is ". When null, values are never quoted.

public char? Quote { get; init; }

Property value

char?

Gets when values are quoted. Default is CsvQuoteMode.AsNeeded.

public CsvQuoteMode QuoteMode { get; init; }

Property value

CsvQuoteMode

Gets the character that separates the values of a row. Default is ,.

public char Separator { get; init; }

Property value

char

Gets a value indicating whether invalid quoting throws a CsvException. Default is false.

public bool Strict { get; init; }

Property value

bool

Remarks

Gets which spaces are removed from the values read. Default is CsvTrimOptions.None.

public CsvTrimOptions Trim { get; init; }

Property value

CsvTrimOptions

TypeInfoResolver

CsvSerializerOptions.cs

Gets the resolver of the metadata of the types, such as a generated CsvSerializerContext. Default is null: the metadata is created with reflection.

public ICsvTypeInfoResolver? TypeInfoResolver { get; init; }

Property value

ICsvTypeInfoResolver?

UnmappedColumnHandling

CsvSerializerOptions.cs

Gets how a column without a member is handled when reading data. Default is CsvUnmappedColumnHandling.Ignore.

public CsvUnmappedColumnHandling UnmappedColumnHandling { get; init; }

Methods

NameDescription
GetTypeInfo(Type)Gets the metadata of a type, from CsvSerializerOptions.TypeInfoResolver or created with reflection.
GetTypeInfo<T>()Gets the metadata of T, from CsvSerializerOptions.TypeInfoResolver or created with reflection.

GetTypeInfo overloads

GetTypeInfo(Type)

CsvSerializerOptions.cs

Gets the metadata of a type, from CsvSerializerOptions.TypeInfoResolver or created with reflection.

[RequiresDynamicCode("Reflection-based CSV serialization is not compatible with trimming and Native AOT. Use a generated CsvSerializerContext and the overloads that take a CsvTypeInfo.")]
[RequiresUnreferencedCode("Reflection-based CSV serialization is not compatible with trimming and Native AOT. Use a generated CsvSerializerContext and the overloads that take a CsvTypeInfo.")]
public CsvTypeInfo GetTypeInfo(Type type)
Parameters
type Type
The type.
Returns

CsvTypeInfo The metadata of the type.

Exceptions
NotSupportedException
The type is not supported.

GetTypeInfo<T>()

CsvSerializerOptions.cs

Gets the metadata of T, from CsvSerializerOptions.TypeInfoResolver or created with reflection.

[RequiresDynamicCode("Reflection-based CSV serialization is not compatible with trimming and Native AOT. Use a generated CsvSerializerContext and the overloads that take a CsvTypeInfo.")]
[RequiresUnreferencedCode("Reflection-based CSV serialization is not compatible with trimming and Native AOT. Use a generated CsvSerializerContext and the overloads that take a CsvTypeInfo.")]
public CsvTypeInfo<T> GetTypeInfo<T>()
Type parameters
T
The type.
Returns

CsvTypeInfo<T> The metadata of the type.

Exceptions
NotSupportedException
The type is not supported.