-
Notifications
You must be signed in to change notification settings - Fork 3
Getting Started
The nuget package is called Net.Code.Csv. After installing this package, you can start reading and writing Csv data.
The two entry points to this library are the ReadCsv
and WriteCsv
static classes.
For the examples, we're assuming a file called "sample.csv" that contains this data
FirstName,LastName,BirthDate
John,Peterson,1980-05-14
To read this CSV file, IDataReader
-style, use the ReadCsv.FromFile
method as follows:
using System;
using Net.Code.Csv;
var reader = ReadCsv.FromFile("sample.csv", hasHeaders: true);
while (reader.Read())
{
string firstName = reader.GetString("FirstName");
string lastName = reader.GetString("LastName");
DateTime birthDate = reader.GetDateTime("BirthDate");
}
This approach will read the data as string fields, and convert them on demand to the requested data types.
NetCsv also has a facility to read data in a strongly typed way. For this, you use the generic overloads ReadCsv.FromFile<T>
, ReadCsv.FromStream<T>
and ReadCsv.FromFile<T>
methods. These will infer schema information from the type and convert the csv records to actual class or record instances:
using System;
using Net.Code.Csv;
record Person(string FirstName, string LastName, [CsvFormat("yyyy-MM-dd")]DateTime BirthDate);
var people = ReadCsv.FromFile<Person>("sample.csv", hasHeaders: true);
foreach (var person in people)
{
string firstName = person.FirstName;
string lastName = person.LastName;
DateTime birthDate = person.BirthDate;
}
Here, the schema is defined by a record Person
with 3 properties (regular classes
are also supported). Note that the CsvFormat
attribute can be used to describe the serialization format of DateTime attributes.
Writing data as CSV is very similar. For example, to write the data above back to a CSV file:
using System;
using Net.Code.Csv;
record Person(string FirstName, string LastName, [CsvFormat("yyyy-MM-dd")]DateTime BirthDate);
var people = new [] { new Person("John", "Peterson", new DateTime(1980, 5, 14)) };
WriteCsv.ToFile("out.csv", people);