public sealed class CsvReader : IDisposable, IAsyncDisposable
Namespace
CsvHelper
Assembly
CsvHelper.dll
Builds
net10.0 netstandard2.1 netstandard2.0 net47

Remarks

Spans returned for a record are valid until the next call to Read or ReadAsync.

A reader is not thread-safe: use it from one thread at a time, and finish each async call before starting the next. Nothing checks this; two threads reading one reader get wrong records, not an exception. To map records on several threads, use ParallelEnumerate<T>(Func<CsvReader, T>, int). The options, the record mappers and the CsvDynamicRecords a reader returns do not change, so they can be shared between threads.

Properties

ByteOffset

Added in v34.0.0
public long ByteOffset { get; }

The offset, in bytes of UTF-8 input, where the current record starts, counted from the start of the input (a byte order mark included), for progress reports and error messages. UTF-16 input (strings, text readers and streams with another encoding) is counted in the bytes of its UTF-8 form.

Property value

long

View source

FieldCount

Added in v34.0.0
public int FieldCount { get; }

The number of fields in the current record.

Property value

int

View source

RawRecord

Added in v34.0.0
public ReadOnlySpan<byte> RawRecord { get; }

The raw bytes of the current record as they appear in the input (UTF-8), without the line break. Empty before the first record and at the end of the input. Valid until the next read.

Property value

View source

RowNumber

Added in v34.0.0
public long RowNumber { get; }

The 1-based number of the current data record (the header is not counted).

Property value

long

View source

Separator

Added in v34.0.0
public char Separator { get; }

The separator in use. When it is detected from the input, getting it before the first Read reads the header (or the start of the input) synchronously. '\0' in CsvMode.FixedWidth mode, which has no separator.

Property value

char

Exceptions

ObjectDisposedException
The separator had to be detected and the reader has been disposed.
CsvFormatException
The separator had to be detected and the header is malformed (see Read).

View source

Indexers

Methods

public static CsvReader Create(ReadOnlyMemory<byte> utf8, CsvReaderOptions? options = null)

Creates a reader over UTF-8 bytes in memory. Array backed memory is read in place without copying.

Parameters

utf8ReadOnlyMemory<byte>
The input. It must not change while the reader is in use. A UTF-16 or UTF-32 byte order mark, or CsvReaderOptions.Encoding, makes the reader transcode it instead.
optionsCsvReaderOptions?
The options, or null for CsvReaderOptions.Default.

Returns

CsvReader
A reader positioned before the header.

Exceptions

ArgumentException
options sets a character that is not ASCII, or uses the same character for two purposes.

View source

Create(byte[], CsvReaderOptions)

Added in v34.0.0static
public static CsvReader Create(byte[] utf8, CsvReaderOptions? options = null)

Creates a reader over UTF-8 bytes in memory. The array is read in place without copying.

Parameters

utf8byte[]
The input. It must not change while the reader is in use. A UTF-16 or UTF-32 byte order mark, or CsvReaderOptions.Encoding, makes the reader transcode it instead.
optionsCsvReaderOptions?
The options, or null for CsvReaderOptions.Default.

Returns

CsvReader
A reader positioned before the header.

Exceptions

ArgumentException
options sets a character that is not ASCII, or uses the same character for two purposes.

View source

public static CsvReader Create(Stream stream, CsvReaderOptions? options = null, bool leaveOpen = false)

Creates a reader over a stream. The stream is read sequentially; it does not need to be seekable.

Parameters

streamStream
The input, read from its current position. A UTF-16 or UTF-32 byte order mark sets its encoding; otherwise it is CsvReaderOptions.Encoding, or UTF-8 when that is not set.
optionsCsvReaderOptions?
The options, or null for CsvReaderOptions.Default. For a CsvSeparatorStream, the separator is its CsvSeparatorStream.Replacement, and the stream takes the quoting, escape and comment rules of these options.
leaveOpenbool
Whether stream stays open when the reader is disposed.

Returns

CsvReader
A reader positioned before the header. Nothing is read from stream until it is needed.

Exceptions

ArgumentNullException
stream is null.
ArgumentException
options sets a character that is not ASCII, or uses the same character for two purposes; or, for a CsvSeparatorStream, sets another separator or FixedWidth mode, or a character its separator contains.
NotSupportedException
stream is a CsvSeparatorStream and CsvReaderOptions.Encoding is neither UTF-8 nor a single-byte encoding.
InvalidOperationException
stream is a CsvSeparatorStream that has already been read from.

View source

public static CsvReader Create(TextReader textReader, CsvReaderOptions? options = null, bool leaveOpen = false)

Creates a reader over UTF-16 text from a TextReader.

Parameters

textReaderTextReader
The input. CsvReaderOptions.Encoding does not apply to it.
optionsCsvReaderOptions?
The options, or null for CsvReaderOptions.Default.
leaveOpenbool
Whether textReader stays open when the reader is disposed.

Returns

CsvReader
A reader positioned before the header. Nothing is read from textReader until it is needed.

Exceptions

ArgumentNullException
textReader is null.
ArgumentException
options sets a character that is not ASCII, or uses the same character for two purposes.

View source

public void Dispose()

Returns the buffers to their pools and disposes the stream or text reader being read, unless the reader was created with leaveOpen. Calling it again does nothing.

View source

DisposeAsync()

Added in v34.0.0
public ValueTask DisposeAsync()

Returns the buffers to their pools and asynchronously disposes the stream or text reader being read, unless the reader was created with leaveOpen. Calling it again does nothing.

Returns

ValueTask
A task that completes when the source has been disposed.

View source

EnumerateRecords<T>(T)

Added in v3.0.0-rc04
public IEnumerable<T> EnumerateRecords<T>(T record) where T : class

Reads the remaining records into record, one instance of a CsvRecordAttribute class that is refilled for every record, so that reading allocates no object per record (strings are still created, unless CsvReaderOptions.PoolStrings shares them). Each step of the enumeration returns the same instance: copy what you keep. The header is read and the columns are resolved by this call.

Type parameters

T
The CsvRecordAttribute class to read.

Parameters

recordT
The instance to refill.

Returns

IEnumerable<T> where T : class
A sequence that reads the next record into record each time it moves, and can be enumerated once.

Exceptions

ArgumentNullException
record is null.
InvalidOperationException
T is not a CsvRecordAttribute type, or this reader is the one a ParallelEnumerate<T>(Func<CsvReader, T>, int) selector got.
NotSupportedException
T has members that only its constructor or an object initializer can set (constructor parameters, init accessors); thrown by the enumeration.
KeyNotFoundException
The header lacks a column that T requires.
ObjectDisposedException
The reader has been disposed.

Remarks

Every member that a record sets is set again: a member whose column is optional and missing from the header keeps the value it has. Members whose type is itself a record type get a new instance for each record.

View source

public IAsyncEnumerable<T> EnumerateRecordsAsync<T>(T record, CancellationToken cancellationToken = default) where T : class

Asynchronously reads the remaining records into record, one instance that is refilled for every record. See EnumerateRecords; as in GetRecordsAsync, every exception is thrown by the enumeration.

Type parameters

T
The CsvRecordAttribute class to read.

Parameters

recordT
The instance to refill.
cancellationTokenCancellationToken
Cancels the reads. A token passed to WithCancellation is combined with this one.

Returns

IAsyncEnumerable<T> where T : class
An asynchronous sequence that reads the next record into record each time it moves, and can be enumerated once.

View source

public static CsvReader FromFile(string path, CsvReaderOptions? options = null, FileOptions fileOptions = FileOptions.SequentialScan)

Opens a file for reading, sharing it with other readers. The reader closes the file when it is disposed. See Create(Stream, CsvReaderOptions, bool).

Parameters

pathstring
The path of the file.
optionsCsvReaderOptions?
The options, or null for CsvReaderOptions.Default.
fileOptionsFileOptions
How the file is opened. The default tells the operating system it is read sequentially.

Returns

CsvReader
A reader positioned before the header.

Exceptions

ArgumentException
path is empty, or options sets a character that is not ASCII, or uses the same character for two purposes.
FileNotFoundException
The file does not exist.
DirectoryNotFoundException
The directory of the file does not exist.
UnauthorizedAccessException
The file cannot be read with the caller's permissions.
IOException
The file cannot be opened, for example because another process is writing it.

View source

FromText(string, CsvReaderOptions)

Added in v34.0.0static
public static CsvReader FromText(string text, CsvReaderOptions? options = null)

Creates a reader over CSV text held in a string.

Parameters

textstring
The input. CsvReaderOptions.Encoding does not apply to it.
optionsCsvReaderOptions?
The options, or null for CsvReaderOptions.Default.

Returns

CsvReader
A reader positioned before the header.

Exceptions

ArgumentException
options sets a character that is not ASCII, or uses the same character for two purposes.

View source

GetChars(int, Span<char>)

Added in v34.0.0
public int GetChars(int index, Span<char> destination)

Copies field index into destination as UTF-16.

Parameters

indexint
The 0-based index of the field.
destinationSpan<char>
Receives the value of the field.

Returns

int
The number of chars written to destination.

Exceptions

ArgumentException
destination is too small for the value.
ArgumentOutOfRangeException
index is negative.

View source

GetFieldIndex(string, int)

Added in v34.0.0
public int GetFieldIndex(string name, int nameIndex)

Gets the index of the column at nameIndex among those with the name. See TryGetFieldIndex(string, int, out int).

Parameters

namestring
The header name of the column.
nameIndexint
0 for the first column with that name, 1 for the second, and so on.

Returns

int
The 0-based index of the column.

Exceptions

ArgumentOutOfRangeException
nameIndex is negative.
KeyNotFoundException
The header does not have that many columns with the name.

View source

GetRawSpan(int)

Added in v34.0.0
public ReadOnlySpan<byte> GetRawSpan(int index)

Gets the raw bytes of field index exactly as they appear in the input.

Parameters

indexint
The 0-based index of the field.

Returns

ReadOnlySpan<byte>
The bytes of the field (UTF-8), including any quotes, escaped quotes, escape characters, padding and surrounding whitespace. Valid until the next read.

Exceptions

ArgumentOutOfRangeException
index is negative.

View source

public T GetRecord<T>()

Reads the current record as a T, a CsvRecordAttribute type. The mapper is created on the first call (reading the header if needed) and reused while T stays the same.

Type parameters

T
The CsvRecordAttribute type to read.

Returns

T
A new T with the values of the current record.

Exceptions

KeyNotFoundException
The header lacks a column that T requires.
CsvFormatException
The record cannot be read, such as a field that cannot be parsed as the type of its member. The exception names the record, the field and the member, and the cause is its Exception.InnerException.

View source

public T GetRecord<T>(CsvRecordMapper<T> mapper)

Reads the current record with mapper, such as a projection that reads only some members (CsvRecordMapper.CreateProjection) or a hand-written mapper. A failure is reported as by GetRecord<T>().

Type parameters

T
The type of the records.

Parameters

mapperCsvRecordMapper<T>
The mapper, created for this reader or for one with the same columns.

Returns

T
The record that mapper read.

Exceptions

ArgumentNullException
mapper is null.
NotSupportedException
The mapper threw it.
CsvFormatException
The record cannot be read, such as a field that cannot be parsed as the type of its member. The exception names the record, the field and the member, and the cause is its Exception.InnerException.

View source

public void GetRecord<T>(T record) where T : class

Reads the current record into record, an existing instance of a CsvRecordAttribute class, instead of creating one. See EnumerateRecords.

Type parameters

T
The CsvRecordAttribute class to read.

Parameters

recordT
The instance whose members are set.

Exceptions

ArgumentNullException
record is null.
NotSupportedException
T has members that only its constructor or an object initializer can set.
KeyNotFoundException
The header lacks a column that T requires.
CsvFormatException
The record cannot be read, such as a field that cannot be parsed as the type of its member. The exception names the record, the field and the member, and the cause is its Exception.InnerException.

View source

public IEnumerable<T> GetRecords<T>()

Reads the remaining records as T, a CsvRecordAttribute type. The header is read and the columns are resolved by this call; the records are read as they are enumerated, and the exceptions of Read are thrown by the enumeration. A record that cannot be read as T throws a CsvFormatException that names the record, the field and the member, with the exception of the field or member as its Exception.InnerException, unless CsvReaderOptions.OnRecordError skips it.

Type parameters

T
The CsvRecordAttribute type to read.

Returns

IEnumerable<T>
A sequence that reads the next record each time it moves, and can be enumerated once.

Exceptions

InvalidOperationException
T is not a CsvRecordAttribute type, or this reader is the one a ParallelEnumerate<T>(Func<CsvReader, T>, int) selector got.
KeyNotFoundException
The header lacks a column that T requires.
ObjectDisposedException
The reader has been disposed.

View source

public IAsyncEnumerable<T> GetRecordsAsync<T>(CancellationToken cancellationToken = default)

Asynchronously reads the remaining records as T, a CsvRecordAttribute type. The header is read and the columns are resolved when the enumeration starts, so every exception, including those of GetRecords, is thrown by the enumeration.

Type parameters

T
The CsvRecordAttribute type to read.

Parameters

cancellationTokenCancellationToken
Cancels the reads. A token passed to WithCancellation is combined with this one.

Returns

IAsyncEnumerable<T>
An asynchronous sequence that reads the next record each time it moves, and can be enumerated once.

View source

GetSpan(int)

Added in v34.0.0
public ReadOnlySpan<byte> GetSpan(int index)

Gets the value of field index of the current record as UTF-8 bytes, decoded as the CsvReaderOptions.Mode says: with quotes removed and escaped quotes unescaped, with escape characters removed, or as the text of its column. The span is valid until the next read.

Parameters

indexint
The 0-based index of the field.

Returns

ReadOnlySpan<byte>
The value of the field as UTF-8 bytes; empty for an empty field.

Exceptions

ArgumentOutOfRangeException
index is negative.

Remarks

A field past the end of the record reads as empty, unless CsvReaderOptions.MissingField is CsvMissingFieldHandling.Throw. The other field accessors behave the same way.

View source

GetSpan(string)

Added in v34.0.0
public ReadOnlySpan<byte> GetSpan(string name)

Gets the value of the field with the given header name. See GetSpan(int).

Parameters

namestring
The header name of the column, matched as by TryGetFieldIndex(string, out int).

Returns

ReadOnlySpan<byte>
The value of the field as UTF-8 bytes; empty for an empty field.

Exceptions

KeyNotFoundException
No column has that name.

View source

GetString(int)

Added in v34.0.0
public string GetString(int index)

Gets field index as a string. With CsvReaderOptions.PoolStrings, a value seen before in the same column may return the same string instance.

Parameters

indexint
The 0-based index of the field.

Returns

string
The value of the field; string.Empty for an empty field.

Exceptions

ArgumentOutOfRangeException
index is negative.

View source

GetString(string)

Added in v34.0.0
public string GetString(string name)

Gets the field with the given header name as a string. See GetString(int).

Parameters

namestring
The header name of the column, matched as by TryGetFieldIndex(string, out int).

Returns

string
The value of the field; string.Empty for an empty field.

Exceptions

KeyNotFoundException
No column has that name.

View source

GetStringOrNull(string)

Added in v34.0.0
public string? GetStringOrNull(string name)

Gets the field with the given header name as a string, or null. See GetStringOrNull(int).

Parameters

namestring
The header name of the column, matched as by TryGetFieldIndex(string, out int).

Returns

string?
The value of the field, or null.

Exceptions

KeyNotFoundException
No column has that name.

View source

IsNull(int)

Added in v34.0.0
public bool IsNull(int index)

Whether field index is null: empty (or missing), or one of CsvReaderOptions.NullValues.

Parameters

indexint
The 0-based index of the field.

Returns

bool
true when the value is empty, the record has no such field or the value is one of CsvReaderOptions.NullValues; otherwise false.

Exceptions

ArgumentOutOfRangeException
index is negative.

View source

ParallelEnumerate<T>(int)

Added in v34.0.0
public IEnumerable<T> ParallelEnumerate<T>(int maxDegreeOfParallelism = -1)

Reads the remaining records as T, a CsvRecordAttribute type, on several threads and returns them in input order. The header is read and the columns are resolved by this call. See ParallelEnumerate<T>(Func<CsvReader, T>, int).

Type parameters

T
The CsvRecordAttribute type to read.

Parameters

maxDegreeOfParallelismint
The number of worker threads, or -1 for one per processor.

Returns

IEnumerable<T>
The records in input order. The sequence can be enumerated once.

Exceptions

ArgumentOutOfRangeException
maxDegreeOfParallelism is 0 or less than -1.
InvalidOperationException
T is not a CsvRecordAttribute type, or this reader is the one a ParallelEnumerate<T>(Func<CsvReader, T>, int) selector got.
KeyNotFoundException
The header lacks a column that T requires.
ObjectDisposedException
The reader has been disposed.

View source

public IEnumerable<T> ParallelEnumerate<T>(Func<CsvReader, T> selector, int maxDegreeOfParallelism = -1)

Maps the remaining records with selector on several threads and returns the results in input order.

Type parameters

T
The type of the results.

Parameters

selectorFunc<CsvReader, T>
Maps the current record of the given reader to a result.
maxDegreeOfParallelismint
The number of worker threads, or -1 for one per processor.

Returns

IEnumerable<T>
The results in input order. The workers start when the enumeration starts, and stop when it ends or is disposed. The sequence can be enumerated once.

Exceptions

ArgumentNullException
selector is null.
ArgumentOutOfRangeException
maxDegreeOfParallelism is 0 or less than -1.
ObjectDisposedException
The reader has been disposed.
InvalidOperationException
This reader is the one a selector got.

Remarks

The selector gets a reader positioned on one record. Use its field accessors (GetString(int), GetSpan(int), Parse<T>(int, Func<string, IFormatProvider, T>) and so on) and return a value; the reader and its spans are only valid during the call, and Read cannot be called on it. Calls run concurrently on different threads, each thread with its own reader. The input is read and checked by one thread at a time, in order, so CsvReaderOptions.OnMalformedRecord is never called concurrently. Exceptions from the reader or the selector are thrown by the enumerator after the results of the preceding records. This reader must not be used otherwise until the enumeration ends.

View source

Parse<T>(int)

Added in v34.0.0

net10.0

public T Parse<T>(int index) where T : ISpanParsable<T>

Parses field index as T with the configured format provider.

Type parameters

T
The type to parse the field as.

Parameters

indexint
The 0-based index of the field.

Returns

T
The parsed value.

Exceptions

FormatException
The field is not a valid T.
OverflowException
The field is outside the range of T.
NotSupportedException
On .NET Framework and .NET Standard, T is not one of the built-in types.
ArgumentOutOfRangeException
index is negative.

Remarks

The built-in types are parsed from the UTF-8 bytes of the field:

On .NET 8 and later, any other type (DateOnly, TimeSpan, BigInteger, your own types) is parsed with its own ISpanParsable<T> parser, from the field decoded to chars. On .NET Framework and .NET Standard, TimeSpan, BigInteger (in NumberStyles.Integer style), char and IPAddress are parsed from the field decoded to a string, as .NET parses them, and other types are not supported: parse them with Parse<T>(int, Func<string, IFormatProvider, T>).

netstandard2.1, netstandard2.0, net47

public T Parse<T>(int index)

Parses field index as T with the configured format provider.

Type parameters

T
The type to parse the field as.

Parameters

indexint
The 0-based index of the field.

Returns

T
The parsed value.

Exceptions

FormatException
The field is not a valid T.
OverflowException
The field is outside the range of T.
NotSupportedException
On .NET Framework and .NET Standard, T is not one of the built-in types.
ArgumentOutOfRangeException
index is negative.

Remarks

The built-in types are parsed from the UTF-8 bytes of the field:

On .NET 8 and later, any other type (DateOnly, TimeSpan, BigInteger, your own types) is parsed with its own ISpanParsable<T> parser, from the field decoded to chars. On .NET Framework and .NET Standard, TimeSpan, BigInteger (in NumberStyles.Integer style), char and IPAddress are parsed from the field decoded to a string, as .NET parses them, and other types are not supported: parse them with Parse<T>(int, Func<string, IFormatProvider, T>).

View source

Parse<T>(string)

Added in v34.0.0

net10.0

public T Parse<T>(string name) where T : ISpanParsable<T>

Parses the field with the given header name as T. See Parse<T>(int).

Type parameters

T
The type to parse the field as.

Parameters

namestring
The header name of the column, matched as by TryGetFieldIndex(string, out int).

Returns

T
The parsed value.

Exceptions

KeyNotFoundException
No column has that name.
FormatException
The field is not a valid T.
OverflowException
The field is outside the range of T.
NotSupportedException
On .NET Framework and .NET Standard, T is not one of the built-in types.

netstandard2.1, netstandard2.0, net47

public T Parse<T>(string name)

Parses the field with the given header name as T. See Parse<T>(int).

Type parameters

T
The type to parse the field as.

Parameters

namestring
The header name of the column, matched as by TryGetFieldIndex(string, out int).

Returns

T
The parsed value.

Exceptions

KeyNotFoundException
No column has that name.
FormatException
The field is not a valid T.
OverflowException
The field is outside the range of T.
NotSupportedException
On .NET Framework and .NET Standard, T is not one of the built-in types.

View source

public T Parse<T>(int index, Func<string, IFormatProvider, T> parser)

Parses field index with parser, which gets the field as a string and the configured format provider, for example reader.Parse(3, TimeSpan.Parse).

Type parameters

T
The type that parser returns.

Parameters

indexint
The 0-based index of the field.
parserFunc<string, IFormatProvider, T>
Parses the value of the field with the given format provider.

Returns

T
The value that parser returns.

Exceptions

ArgumentNullException
parser is null.
ArgumentOutOfRangeException
index is negative.

View source

net10.0

public T Parse<T>(int index, IFormatProvider provider) where T : ISpanParsable<T>

Parses field index as T with provider instead of the configured format provider. See Parse<T>(int).

Type parameters

T
The type to parse the field as.

Parameters

indexint
The 0-based index of the field.
providerIFormatProvider
The format provider to parse with.

Returns

T
The parsed value.

Exceptions

ArgumentNullException
provider is null.
FormatException
The field is not a valid T.
OverflowException
The field is outside the range of T.
NotSupportedException
On .NET Framework and .NET Standard, T is not one of the built-in types.
ArgumentOutOfRangeException
index is negative.

netstandard2.1, netstandard2.0, net47

public T Parse<T>(int index, IFormatProvider provider)

Parses field index as T with provider instead of the configured format provider. See Parse<T>(int).

Type parameters

T
The type to parse the field as.

Parameters

indexint
The 0-based index of the field.
providerIFormatProvider
The format provider to parse with.

Returns

T
The parsed value.

Exceptions

ArgumentNullException
provider is null.
FormatException
The field is not a valid T.
OverflowException
The field is outside the range of T.
NotSupportedException
On .NET Framework and .NET Standard, T is not one of the built-in types.
ArgumentOutOfRangeException
index is negative.

View source

public T Parse<T>(string name, Func<string, IFormatProvider, T> parser)

Parses the field with the given header name with parser. See Parse<T>(int, Func<string, IFormatProvider, T>).

Type parameters

T
The type that parser returns.

Parameters

namestring
The header name of the column, matched as by TryGetFieldIndex(string, out int).
parserFunc<string, IFormatProvider, T>
Parses the value of the field with the given format provider.

Returns

T
The value that parser returns.

Exceptions

ArgumentNullException
name or parser is null.
KeyNotFoundException
No column has that name.

View source

ParseExact<T>(int, string)

Added in v34.0.0
public T ParseExact<T>(int index, string format)

Parses field index as a DateTime or DateTimeOffset in exactly the given format, such as "yyyyMMdd", with the configured format provider. A time zone offset or Z in the field gives a DateTimeKind.Local or DateTimeKind.UtcDateTime as DateTimeStyles.RoundtripKind describes; a DateTimeOffset field without an offset gets the local time zone's.

Type parameters

Parameters

indexint
The 0-based index of the field.
formatstring
The format of the field, as DateTime.ParseExact(string, string, IFormatProvider) takes it.

Returns

T
The parsed value.

Exceptions

ArgumentNullException
format is null.
FormatException
The field does not have the format, or the format is not valid.
ArgumentOutOfRangeException
index is negative.

View source

ParseExact<T>(int, string[])

Added in v34.0.0
public T ParseExact<T>(int index, string[] formats)

Parses field index as a DateTime or DateTimeOffset in exactly one of the given formats, tried in order, such as "yyyy-MM-dd" and "dd/MM/yyyy" for a file that mixes them, with the configured format provider. See ParseExact<T>(int, string).

Type parameters

Parameters

indexint
The 0-based index of the field.
formatsstring[]
The formats the field may have, as DateTime.ParseExact(string, string[], IFormatProvider, DateTimeStyles) takes them.

Returns

T
The parsed value.

Exceptions

ArgumentNullException
formats is null.
FormatException
The field has none of the formats, or a format is not valid.
ArgumentOutOfRangeException
index is negative.

View source

public T ParseExact<T>(int index, string format, IFormatProvider provider)

Parses field index as a DateTime or DateTimeOffset in exactly the given format with provider. See ParseExact<T>(int, string).

Type parameters

Parameters

indexint
The 0-based index of the field.
formatstring
The format of the field, as DateTime.ParseExact(string, string, IFormatProvider) takes it.
providerIFormatProvider
The format provider to parse with.

Returns

T
The parsed value.

Exceptions

ArgumentNullException
format or provider is null.
FormatException
The field does not have the format, or the format is not valid.
ArgumentOutOfRangeException
index is negative.

View source

public T ParseExact<T>(int index, string[] formats, IFormatProvider provider)

Parses field index as a DateTime or DateTimeOffset in exactly one of the given formats, tried in order, with provider. See ParseExact<T>(int, string[]).

Type parameters

Parameters

indexint
The 0-based index of the field.
formatsstring[]
The formats the field may have, as DateTime.ParseExact(string, string[], IFormatProvider, DateTimeStyles) takes them.
providerIFormatProvider
The format provider to parse with.

Returns

T
The parsed value.

Exceptions

ArgumentNullException
formats or provider is null.
FormatException
The field has none of the formats, or a format is not valid.
ArgumentOutOfRangeException
index is negative.

View source

public bool Read()

Advances to the next record, reading the header first if it has not been read. Empty lines, comments and the records that the options say to skip are passed over.

Returns

bool
true when the reader is positioned on a record; false at the end of the input.

Exceptions

CsvFormatException
A record is malformed and CsvReaderOptions.MalformedData or CsvReaderOptions.FieldCountMismatch is set to throw, or a record is too large to buffer.
ObjectDisposedException
The reader has been disposed.

View source

ReadAsync(CancellationToken)

Added in v34.0.0
public ValueTask<bool> ReadAsync(CancellationToken cancellationToken = default)

Asynchronously advances to the next record, reading the header first if it has not been read. Completes synchronously while records that have already been read from the source remain. See Read.

Parameters

cancellationTokenCancellationToken
Cancels reading from the source.

Returns

ValueTask<bool>
true when the reader is positioned on a record; false at the end of the input.

Exceptions

CsvFormatException
A record is malformed and CsvReaderOptions.MalformedData or CsvReaderOptions.FieldCountMismatch is set to throw, or a record is too large to buffer.
ObjectDisposedException
The reader has been disposed.
OperationCanceledException
cancellationToken was canceled.

View source

public void ReadHeader()

Reads the header row (if any) without advancing to the first data record. Without a header, it still reads the start of the input, so that Separator is known. Once the header has been read, calling it while the reader is on a record makes that record the new header, for files with several data sets one after the other: Headers, the by-name lookups and the record mappers created afterwards use it, and the record does not count as a data record. Otherwise it does nothing.

Exceptions

CsvFormatException
The header is malformed and the options say to throw (see Read).
ObjectDisposedException
The reader has been disposed.

View source

public ValueTask ReadHeaderAsync(CancellationToken cancellationToken = default)

Asynchronously reads the header row (if any) without advancing to the first data record, or makes the current record the new header. See ReadHeader.

Parameters

cancellationTokenCancellationToken
Cancels reading from the source.

Returns

ValueTask
A task that completes when the header has been read.

Exceptions

CsvFormatException
The header is malformed and the options say to throw (see Read).
ObjectDisposedException
The reader has been disposed.
OperationCanceledException
cancellationToken was canceled.

View source

public bool TryGetFieldIndex(string name, out int index)

Finds the index of the column with the given header name. An exact match wins; otherwise the name is matched ignoring case and surrounding whitespace. Both names are changed by CsvReaderOptions.NormalizeHeaderName first, if it is set. Reads the header first if it has not been read (see ReadHeader).

Parameters

namestring
The header name of the column.
indexint
The 0-based index of the column, or 0 when it is not found.

Returns

bool
Whether a column has that name.

Exceptions

Remarks

When several columns have the same name, the first one wins; TryGetFieldIndex(string, int, out int) finds the others. Without a header (CsvReaderOptions.HasHeader is false), no name is found.

View source

public bool TryGetFieldIndex(string name, int nameIndex, out int index)

Finds the index of a column whose name several columns have: the one at nameIndex among them, in header order. Names are matched as by TryGetFieldIndex(string, out int): among the exact matches when there are enough, else among those that match ignoring case and surrounding whitespace.

Parameters

namestring
The header name of the column.
nameIndexint
0 for the first column with that name, 1 for the second, and so on.
indexint
The 0-based index of the column, or 0 when it is not found.

Returns

bool
Whether the header has that many columns with the name.

Exceptions

ArgumentOutOfRangeException
nameIndex is negative.

View source

public bool TryGetRecord<T>(CsvRecordMapper<T> mapper, out T record)

Reads the current record with mapper, as GetRecord<T>(CsvRecordMapper<T>) does, unless it cannot be read and CsvReaderOptions.OnRecordError skips it, as GetRecords skips such records.

Type parameters

T
The type of the records.

Parameters

mapperCsvRecordMapper<T>
The mapper, created for this reader or for one with the same columns.
recordT
The record, or the default of T when it was skipped.

Returns

bool
true when the record was read; false when the handler skipped it.

Exceptions

ArgumentNullException
mapper is null.
NotSupportedException
The mapper threw it.
CsvFormatException
The record cannot be read and there is no CsvReaderOptions.OnRecordError, or it does not skip the record. The exception names the record, the field and the member, and the cause is its Exception.InnerException.

View source

TryParse<T>(int, out T)

Added in v34.0.0

net10.0

public bool TryParse<T>(int index, out T value) where T : ISpanParsable<T>

Tries to parse field index as T. See Parse<T>(int).

Type parameters

T
The type to parse the field as.

Parameters

indexint
The 0-based index of the field.
valueT
The parsed value, or the default of T when parsing fails.

Returns

bool
Whether the field could be parsed.

Exceptions

NotSupportedException
On .NET Framework and .NET Standard, T is not one of the built-in types.
ArgumentOutOfRangeException
index is negative.

netstandard2.1, netstandard2.0, net47

public bool TryParse<T>(int index, out T value)

Tries to parse field index as T. See Parse<T>(int).

Type parameters

T
The type to parse the field as.

Parameters

indexint
The 0-based index of the field.
valueT
The parsed value, or the default of T when parsing fails.

Returns

bool
Whether the field could be parsed.

Exceptions

NotSupportedException
On .NET Framework and .NET Standard, T is not one of the built-in types.
ArgumentOutOfRangeException
index is negative.

View source

public bool TryParse<T>(int index, CsvTryParser<T> parser, out T value)

Tries to parse field index with parser, which gets the field as a string and the configured format provider.

Type parameters

T
The type that parser parses.

Parameters

indexint
The 0-based index of the field.
parserCsvTryParser<T>
Tries to parse the value of the field with the given format provider.
valueT
The value that parser produced.

Returns

bool
The result of parser: whether the field could be parsed.

Exceptions

ArgumentNullException
parser is null.
ArgumentOutOfRangeException
index is negative.

View source

public bool TryValidateHeader<T>(out IReadOnlyList<string> missingColumns)

Checks, without reading a record and without throwing, that the header has every column that T requires; see ValidateHeader.

Type parameters

Parameters

missingColumnsIReadOnlyList<string>
The missing columns, as the message of ValidateHeader names them: the member and the header name it looks for, such as Order.Price ('Unit Price'). Empty when none is missing.

Returns

bool
Whether the header has every required column.

Exceptions

ObjectDisposedException
The reader has been disposed.

View source

ValidateHeader<T>()

Added in v3.0.0-rc01
public void ValidateHeader<T>()

Checks, without reading a record, that the header has every column that T requires: the check that GetRecords makes. The header is read if it has not been.

Type parameters

Exceptions

KeyNotFoundException
The header lacks columns that T requires, which the message names, or the input has no header and required members have no column index.
ObjectDisposedException
The reader has been disposed.

View source