-
Notifications
You must be signed in to change notification settings - Fork 3
Custom formatting
Jeroen Haegebaert edited this page Nov 13, 2020
·
2 revisions
Date and time values are often formatted in localized ways. Also boolean values are sometimes formatted with other strings that 'true' and 'false' (e.g. 'Y' and 'N').
In NetCsv, the CsvFormat
is available to specify either DateTime/DateTimeOffset or Boolean columns.
For DateTime and DateTimeOffset properties, any .Net format string for date/times can be used. For boolean values, a custom format string in the form of "true|false"
can be used.
Suppose you have the following CSV file:
Name;IsActive;BirthDate
John;Y;19801105
Jake;N;19750315
This data can be read (& written) to/from a class like so:
public class User
{
public string Name { get; set; }
[CsvFormat("yyyyMMdd")]
public DateTime BirthDate { get; set; }
[CsvFormat("Y|N")]
public bool IsActive { get; set; }
}
var users = ReadCsv.FromString<User>(data, delimiter: ';', hasHeaders: true).ToList();
var roundtripData = WriteCsv.ToString(users, delimiter: ';', hasHeaders: true);