-
Notifications
You must be signed in to change notification settings - Fork 3
Working with schemas
NetCsv has a facility to define a schema for your csv file in code: the CsvSchema
, which contains a collection of CsvColumn
instances.
In most cases, you will simply define a class or record to define the schema of your data, but in case that doesn't cut it, you can also manually create a schema using the CsvSchemaBuilder
class. Suppose again we have a csv file with data that looks like this:
FirstName,LastName,BirthDate
John,Peterson,1980-05-13
The schema for this data file can be built as follows:
var schema = new CsvSchemaBuilder(CultureInfo.InvariantCulture)
.AddString(nameof(Person.FirstName))
.AddString(nameof(Person.LastName), allowNull: true)
.AddDateTime(nameof(Person.BirthDate), format: "yyyy-MM-dd")
.Schema;
For each AddX
method, you can specify whether the column should allow null values. As you can see, the AddDateTime
method also has a parameter to specify the format in which the column is serialized. See custom formatting for more information.
However, as stated before, a far easier way to build a schema is to use the CsvSchemaBuilder.From<T>
method, which will automatically generate the schema via reflection. And in most cases, by using the generic methods on ReadCsv
and WriteCsv
, you won't need to worry about schema's at all.