CsvSerializerOptions Class
Options that control how CsvSerializer reads and writes records.
public sealed class CsvSerializerOptionsRemarks
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
| Name | Description |
|---|---|
| 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.csInitializes a new instance of the CsvSerializerOptions class with the default values.
public CsvSerializerOptions()CsvSerializerOptions(CsvSerializerOptions)
CsvSerializerOptions.csInitializes a new instance of the CsvSerializerOptions class with the values of other options.
public CsvSerializerOptions(CsvSerializerOptions options)Parameters
optionsCsvSerializerOptions- The options to copy.
Properties
| Name | Description |
|---|---|
| BadDataHandler | Gets the method called for malformed data, which decides whether the serializer throws, accepts the data, or skips the record. Default is null. |
| BufferSize | Gets the size of the buffers of the readers and the writers. Default is 16384. |
| CommentCharacter | Gets the character that starts a comment line, or null when the data has no comments. Default is null. |
| Converters | Gets the converters used before the built-in converters. Default is an empty list. |
| Default | Gets the default options. |
| DeserializationErrorHandler | 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. |
| EscapeFormulas | Gets a value indicating whether string values that a spreadsheet would run as a formula are escaped. Default is false. |
| FormatProvider | Gets the format provider used to parse and format values. Default is null, which means CultureInfo.InvariantCulture. |
| HasHeaderRow | Gets a value indicating whether the first row holds the names of the columns. Default is true. |
| IncludeFields | Gets a value indicating whether public fields are serialized. Default is false. |
| MaxDegreeOfParallelism | Gets the maximum number of threads that convert the records to objects when reading data. Default is 1. |
| MaxRowLength | Gets the maximum length of a row read from a TextReader or a Stream. Default is 16777216. |
| MissingColumnHandling | Gets how a member without a column is handled when reading data with a header row. Default is CsvMissingColumnHandling.Ignore. |
| NewLine | Gets the string written at the end of each row. Default is \r\n. |
| PropertyNameCaseInsensitive | Gets a value indicating whether the names of the columns are matched ignoring case. Default is false. |
| PropertyNamingPolicy | 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. |
| Quote | Gets the character that quotes values. Default is ". When null, values are never quoted. |
| QuoteMode | Gets when values are quoted. Default is CsvQuoteMode.AsNeeded. |
| Separator | Gets the character that separates the values of a row. Default is ,. |
| Strict | Gets a value indicating whether invalid quoting throws a CsvException. Default is false. |
| Trim | Gets which spaces are removed from the values read. Default is CsvTrimOptions.None. |
| TypeInfoResolver | Gets the resolver of the metadata of the types, such as a generated CsvSerializerContext. Default is null: the metadata is created with reflection. |
| UnmappedColumnHandling | Gets how a column without a member is handled when reading data. Default is CsvUnmappedColumnHandling.Ignore. |
BadDataHandler
CsvSerializerOptions.csGets 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
Remarks
See CsvReaderOptions.BadDataHandler. To handle the values that cannot be converted, use CsvSerializerOptions.DeserializationErrorHandler.
BufferSize
CsvSerializerOptions.csCommentCharacter
CsvSerializerOptions.csConverters
CsvSerializerOptions.csGets the converters used before the built-in converters. Default is an empty list.
public IReadOnlyList<CsvConverter> Converters { get; init; }Property value
Default
CsvSerializerOptions.csDeserializationErrorHandler
CsvSerializerOptions.csGets 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);EscapeFormulas
CsvSerializerOptions.csGets a value indicating whether string values that a spreadsheet would run as a formula are escaped. Default is false.
public bool EscapeFormulas { get; init; }FormatProvider
CsvSerializerOptions.csGets the format provider used to parse and format values. Default is null, which means CultureInfo.InvariantCulture.
public IFormatProvider? FormatProvider { get; init; }Property value
HasHeaderRow
CsvSerializerOptions.csIncludeFields
CsvSerializerOptions.csMaxDegreeOfParallelism
CsvSerializerOptions.csGets 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.
MaxRowLength
CsvSerializerOptions.csGets the maximum length of a row read from a TextReader or a Stream. Default is 16777216.
public int MaxRowLength { get; init; }Property value
MissingColumnHandling
CsvSerializerOptions.csGets how a member without a column is handled when reading data with a header row. Default is CsvMissingColumnHandling.Ignore.
public CsvMissingColumnHandling MissingColumnHandling { get; init; }Property value
NewLine
CsvSerializerOptions.csPropertyNameCaseInsensitive
CsvSerializerOptions.csPropertyNamingPolicy
CsvSerializerOptions.csGets 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
QuoteMode
CsvSerializerOptions.csGets when values are quoted. Default is CsvQuoteMode.AsNeeded.
public CsvQuoteMode QuoteMode { get; init; }Property value
Separator
CsvSerializerOptions.csStrict
CsvSerializerOptions.csGets a value indicating whether invalid quoting throws a CsvException. Default is false.
public bool Strict { get; init; }Gets which spaces are removed from the values read. Default is CsvTrimOptions.None.
public CsvTrimOptions Trim { get; init; }Property value
TypeInfoResolver
CsvSerializerOptions.csGets 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
UnmappedColumnHandling
CsvSerializerOptions.csGets how a column without a member is handled when reading data. Default is CsvUnmappedColumnHandling.Ignore.
public CsvUnmappedColumnHandling UnmappedColumnHandling { get; init; }Property value
Methods
| Name | Description |
|---|---|
| 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.csGets 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
typeType- The type.
Returns
CsvTypeInfo The metadata of the type.
Exceptions
NotSupportedException- The type is not supported.
GetTypeInfo<T>()
CsvSerializerOptions.csGets 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.