I'm using the FileHelpers 2.0 library to write a CSV file using the ClassBuilder
class to generate a record type.
My data contains dates and so I create a field of type DateTime
, but when the file is generated the date values come out in the format ddmmyyyy
rather than dd/mm/yyyy
e.g. 28042000
instead of 28/04/2000
.
I've set the DateFormat
property of the CsvOptions
class to "dd/MM/yyyy"
but it doesn't help.
Here is the code that generates the record type:
private Type CreateRecordType()
{
int propertyIndex = 0;
var csvOptions = new CsvOptions("Flat" + _report.RootType.Name, ',', Properties.Count)
{
DateFormat = "dd/MM/yyyy"
};
var classBuilder = new CsvClassBuilder(csvOptions);
foreach(var property in Properties)
{
var fieldBuilder = classBuilder.FieldByIndex(propertyIndex++);
fieldBuilder.FieldName = property.Name;
fieldBuilder.FieldType = property.Type.Name;
}
return classBuilder.CreateRecordClass();
}
It turns out you need to use the Converter
property of the FieldBuilder
class.
Adding the following block of code to my method allows me to customise the date format in the resulting CSV file.
if (property.Type == typeof(DateTime))
{
fieldBuilder.Converter.Kind = ConverterKind.Date;
fieldBuilder.Converter.Arg1 = "dd/MM/yyyy";
}